I am trying to remove a timestamp (formatted as numbers dash numbers) from a string. In the process I experimented with global RegExp. I came up with the following code:
for(let filename of ["123-123_aaa_bbb_ccc","aaa_bbb_ccc_129-999"])
{
let s=filename.split("_")
let globalRegex = new RegExp('^\d+\-\d+$', 'g');
for(let si of s){
if(globalRegex.test(si)) break
}
console.log(`match found at: `,globalRegex.lastIndex)
}
which returns:
match found at: 0
match found at: 0
My questions are:
There are quite a few issues here:
0s because your regex does not match, and it does not match because you defined the regex string inside a regular string literal, thus, losing all single backslashes. The pattern must be set with a regex literal, let globalRegex = /^\d+\-\d+$/; (see Why this javascript regex doesn't work?). Note the absence of the g flag, if you use it with RegExp#test(), you must not use g flag to avoid issues (see Why does a RegExp with global flag give wrong results?).0s as output because a /^\d+\-\d+$/ regex can and will only match at the start of the string (Index=0). You seeem to want to get the IDs of the "words" or "tokens" in the string, so you need to count them.So, you could re-write the code as
for(let filename of ["123-123_aaa_bbb_ccc","aaa_bbb_ccc_129-999"])
{
let result = -1;
let s=filename.split("_")
let globalRegex = /^\d+\-\d+$/;
for (const [index, si] of s.entries()) {
if(globalRegex.test(si)) {
result = index
break
}
}
console.log(`match found at: `, result)
}