regular expression javascript with RegExp - javascript

I read on RegExp in javascript
And I see two ways to create new RegExp:/ab+c/i;
new RegExp('ab+c', 'i');
new RegExp(/ab+c/, 'i');
But I want to create new RegExp like this:
var re = new RegExp(`\d+${variable}`, 'g');
I try but it's not working. How can I do that?

Escape your RegExp character class in the template literal with a \\, e.g. to escape:
\d, write \\d
\w, write \\w
\s, write \\s
...and so on.
let variable = 1;
const re = new RegExp(`\\d+${variable}`, 'g');
console.log(re);
More on RegeExp

You can write the whole expression as a string (to which you can concatenate the value of the variable), then use eval() to change it to a working javascript expression:
var x = "A";
var re = eval("new RegExp('\d+$" + x + "', 'g')");

Related

Placing variable in JavaScript regex

I've got a regular expression like this one:
var reg = /http:\/\/s(\d+)\.de\.example\.com\/(.*?)\.php(.*)/i;
I want to have a variable, exactly this: ccode[i][2] in place of .de.
How do I do that? Thank for your help.
You need to use a RegExp constructor notation if you want to use variables in your regex pattern, and inside it, you need to double escape special regex metacharacters. I.e.
var reg = new RegExp("http://s(\\d+)\\." + ccode[i][2] + "\\.example\\.com/(.*?)\\.php(.*)", "i");
From MDN:
Use the constructor function when you know the regular expression pattern will be changing, or you don't know the pattern and are getting it from another source, such as user input.
Sample code:
var ccode = "de";
var reg = new RegExp("http://s(\\d+)\\." + ccode + "\\.example\\.com/(.*?)\\.php(.*)", "i");
alert(reg.test("http://s123.de.example.com/something.php?some=params"));
Try this
var reg = '/http:\/\/s(\d+)\\'+ccode[i][2]+'\.example\.com\/(.*?)\.php(.*)/i';

Matching a string with a regex gives null even though it should match

I am trying to get my regex to work in JavaScript, but I have a problem.
Code:
var reg = new RegExp('978\d{10}');
var isbn = '9788740013498';
var res = isbn.match(reg);
console.log(res);
However, res is always null in the console.
This is quite interesting, as the regex should work.
My question: then, what is the right syntax to match a string and a regex?
(If it matters and could have any say in the environment: this code is taken from an app.get view made in Express.js in my Node.js application)
Because you're using a string to build your regex, you need to escape the \. It's currently working to escape the d, which doesn't need escaping.
You can see what happens if you create your regex on the chrome console:
new RegExp('978\d{10}');
// => /978d{10}/
Note that there is no \d, only a d, so your regex matches 978dddddddddd. That is, the literal 'd' character repeated 10 times.
You need to use \\ to insert a literal \ in the string you're building the regex from:
var reg = new RegExp('978\\d{10}');
var isbn = '9788740013498';
var res = isbn.match(reg);
console.log(res)
// => ["9788740013498", index: 0, input: "9788740013498"]
You need to escape with double back slash if you use RegExp constructor:
var reg = new RegExp('978\\d{10}');
Quote from documentation:
When using the constructor function, the normal string escape rules (preceding special characters with \ when included in a string) are necessary. For example, the following are equivalent:
var re = /\w+/;
var re = new RegExp("\\w+");

javascript syntax for regex using variable as pattern

I have a variable patt with a dynamic numerical value
var patt = "%"+number+":";
What is the regex syntax for using it in the test() method?
I have been using this format
var patt=/testing/g;
var found = patt.test(textinput);
TIA
Yeah, you pretty much had it. You just needed to pass your regex string into the RegExp constructor. You can then call its test() function.
var matcher = new RegExp("%" + number + ":", "g");
var found = matcher.test(textinput);
Hope that helps :)
You have to build the regex using a regex object, rather than the regex literal.
From your question, I'm not exactly sure what your matching criteria is, but if you want to match the number along with the '%' and ':' markers, you'd do something like the following:
var matcher = new RegExp("%" + num_to_match + ":", "g");
You can read up more here:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp
You're on the right track
var testVar = '%3:';
var num = 3;
var patt = '%' + num + ':';
var result = patt.match(testVar);
alert(result);
Example: http://jsfiddle.net/jasongennaro/ygfQ8/2/
You should not use number. Although it is not a reserved word, it is one of the predefined class/object names.
And your pattern is fine without turning it into a regex literal.
These days many people enjoy ES6 syntax with babel. If this is your case then there is an option without string concatenation:
const matcher = new RegExp(`%${num_to_match}:`, "g");

Match whitespace in Javascript regexp by object, created through RegExp constructor

Please, look into this code. Why does creating of the same regular expression by different ways (by /regex/ literal and through RegExp constructor) cause different result? Why doesn't the second pattern match the whitespace in the str?
var str = " ";
var pat1 = /\s/;
document.writeln(pat1.test(str)); // shows "true"
var pat2 = new RegExp("\s");
document.writeln(pat2.test(str)); // shows "false"
Can't find the answer on my question anywhere. Thanks
You need to escape the backslash since it's in a string:
var pat2 = new RegExp("\\s");

How to use variables inside Regular Expression in Javascript

I want to build a RegEx in JavaScript that matches a word but not part of it. I think that something like \bword\b works well for this. My problem is that the word is not known in advance so I would like to assemble the regular expression using a variable holding the word to be matched something along the lines of:
r = "\b(" + word + ")\b";
reg = new RegExp(r, "g");
lexicon.replace(reg, "<span>$1</span>"
which I noticed, does not work. My idea is to replace specific words in a paragraph with a span tag. Can someone help me?
PS: I am using jQuery.
\ is an escape character in regular expressions and in strings.
Since you are assembling the regular expression from strings, you have to escape the \s in them.
r = "\\b(" + word + ")\\b";
should do the trick, although I haven't tested it.
You probably shouldn't use a global for r though (and probably not for reg either).
You're not escaping the backslash. So you should have:
r = "\\b(" + word + ")\\b"; //Note the double backslash
reg = new RegExp(r, "g");
Also, you should escape special characters in 'word', because you don't know if it can have regex special characters.
Hope this helps. Cheers
And don't write expressions in the regexp variable, because it does not work!
Example(not working):
var r = "^\\w{0,"+ maxLength-1 +"}$"; // causes error
var reg = new RegExp(r, "g");
Example, which returns the string as expected:
var m = maxLength - 1;
var r = "^\\w{0,"+ m +"}$";
var reg = new RegExp(r, "g");
Use this
r = "(\\\b" +word+ "\\\b)"

Categories

Resources