Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

build Regex string with js

<script>
var String = "1 Apple and 13 Oranges";
var regex = /[^\d]/g;
var regObj = new RegExp(regex);
document.write(String.replace(regObj,'')); 
</script>

And it works fine - return all the digits in the string.

However when I put quote marks around the regex like this:

var regex = "/[^\d]/g"; This doesn't work.

How can I turn a string to a working regex in this case?

Thanks

like image 668
Bobbi X Avatar asked Feb 18 '23 08:02

Bobbi X


2 Answers

You can create regular expressions in two ways, using the regular expression literal notation, or RegExp constructor. It seems you have mixed up the two. :)

Here is the literal way:

var regex = /[^\d]/g;

In this case you don't have use quotes. / characters at the ends serve as the delimiters, and you specify the flags at the end.

Here is how to use the RegExp constructor, in which you pass the pattern and flags (optional) as string. When you use strings you have to escape any special characters inside it using a '\'.

Since the '\' (backslash) is a special character, you have to escape the backslash using another backslash if you use double quotes.

var regex = new RegExp("[^\\d]", "g");

Hope this makes sense.

like image 197
BuddhiP Avatar answered Feb 27 '23 07:02

BuddhiP


As slash(\) has special meaning for strings (e.g. "\n","\t", etc...), you need to escape that simbol, when you are passing to regexp:

var regex = "[^\\d]";

Also expression flags (e.g. g,i,etc...) must be passed as separate parameter for RegExp. So overall:

var regex = "[^\\d]";
var flags = "g";
var regObj = new RegExp(regex, flags);
like image 44
Engineer Avatar answered Feb 27 '23 07:02

Engineer