Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaScript regex.exec() should intended to use an assembled regEx

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 ):

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading