if I use ( https://jsfiddle.net/fgsvzn4a/ ) :
var text = "ui1pu";
var regExParameter = '\d ';
var regEx = '/(.*)' regExParameter '(.*)/gi';
var matches = regEx.exec(text);
if(matches && matches[1]) {
var str1 = matches[1];
var str2 = matches[2];
var newStr = str1 str2
console.log(newStr);
}
i get this error:
Paused on exception
TypeError: regEx.exec is not a function
this prototype is working (inspired by https://stackoverflow.com/a/15845184/2891692 ):
var text = "my1bla";
var matches = /(my)\d (.*)/gi.exec(text);
if(matches && matches[1]) {
var str1 = matches[1];
var str2 = matches[2];
var newStr = str1 str2
alert(newStr);
}
but i want to use input parameters to build the regex (first example).
i get ReferenceError: Regex is not defined
if i try this:
var text = "ui1pu";
var regExParameter = '\d ';
var regExString = '/(.*)' regExParameter '(.*)/gi';
var regEx = new Regex(regExString);
var matches = regEx.exec(text);
if(matches && matches[1]) {
var str1 = matches[1];
var str2 = matches[2];
var newStr = str1 str2
console.log(newStr);
}
any idea?
CodePudding user response:
Use the RegExp
constructor. Note that the slashes should be omitted from the string and the flags should be passed as the second argument.
var text = "ui1pu";
var regExParameter = '\\d ';
var regExString = '(.*)' regExParameter '(.*)';
var regEx = new RegExp(regExString, 'gi');
var matches = regEx.exec(text);
if(matches && matches[1]) {
var str1 = matches[1];
var str2 = matches[2];
var newStr = str1 str2
console.log(newStr);
}