1

I am trying to update a project that detects a value such as ts-english, ts-german, ts-italian using regular expression. this code produces

var str = "ts-english";
let patt = /(?<=ts\-)\S+/i;
var res = patt.exec(str);
console.log (res)

output: [ 'english', index: 3, input: 'ts-english', groups: undefined ]

I want to be able to do the some thing for ts-1-english in a for loop. I understand I am supposed to use RegEx to set the variable during each iteration of the loop.

var str = "ts-1-english";
for (q=1; q <= 3; q++){
    var mpatt = new RegExp ("/(?<=ts\\-" + q + "\\-)\\S+/i")
    console.log (mpatt)
    var res = mpatt.exec(str);
    console.log ("q: " + (q) + " result of test: " + res)
}

this is my output.

//(?<=ts-1-)\S+/i/ q: 1 result of test: null

//(?<=ts-2-)\S+/i/ q: 2 result of test: null

//(?<=ts-3-)\S+/i/ q: 3 result of test: null

Community
  • 1
  • 1

1 Answers1

0

The problem with your code is that when you use new RegExp, you should pass the plain regular expression you want to construct, without / delimiters, and without flags. To use flags, pass them in the second argument, for example:

new RegExp ("(?<=ts\\-" + q + "\\-)\\S+", 'i');

But it's much easier to use regular expression literals when possible; you don't have to double-escape backslashes, among other things. And, in this case, it is possible. Rather than using a loop, you can instead use a character set that matches either 1, 2, or 3 at the desired point, with [1-3]:

const str = "ts-1-english";
const mpatt = /(?<=ts-[1-3]-)\S+/i;
const res = mpatt.exec(str);
console.log(res)

Also note that lookbehind in Javascript isn't widely supported; you might consider using group for the part you want to extract instead:

const str = "ts-1-english";
const mpatt = /ts-[1-3]-(\S+)/i;
const res = mpatt.exec(str);
console.log(res);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320