JavaScript regex pattern concatenate with variable
var re = new RegExp("/\b"+test+"\b/");
\b
in a string literal is a backspace character. When putting a regex in a string literal you need one more round of escaping:var re = new RegExp("\\b"+test+"\\b");
(You also don't need the //
in this context.) Use dynamic (variable) string as regex pattern in JavaScript
To create the regex from a string, you have to use JavaScript's RegExp
object.
If you also want to match/replace more than one time, then you must add the g
(global match) flag. Here's an example:
var stringToGoIntoTheRegex = "abc";
var regex = new RegExp("#" + stringToGoIntoTheRegex + "#", "g");
// at this point, the line above is the same as: var regex = /#abc#/g;
var input = "Hello this is #abc# some #abc# stuff.";
var output = input.replace(regex, "!!");
alert(output); // Hello this is !! some !! stuff.
JSFiddle demo here.In the general case, escape the string before using as regex:
Not every string is a valid regex, though: there are some speciall characters, like(
or [
. To work around this issue, simply escape the string before turning it into a regex. A utility function for that goes in the sample below:function escapeRegExp(stringToGoIntoTheRegex) {
return stringToGoIntoTheRegex.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
var stringToGoIntoTheRegex = escapeRegExp("abc"); // this is the only change from above
var regex = new RegExp("#" + stringToGoIntoTheRegex + "#", "g");
// at this point, the line above is the same as: var regex = /#abc#/g;
var input = "Hello this is #abc# some #abc# stuff.";
var output = input.replace(regex, "!!");
alert(output); // Hello this is !! some !! stuff.
JSFiddle demo here.Note: the regex in the question uses the
s
modifier, which didn't exist at the time of the question, but does exist -- a s
(dotall) flag/modifier in JavaScript -- today. concat variable in regexp pattern
You need to build your regex as a string and pass it to the RegExp
constructor:
var regexString = '\\d{' + number + '}';
var regex = new RegExp(regexString);
var p = str.match(regex);
Notice that when building a regex via a string, you need to add some extra escape characters to escape the string as well as the regex. How to concat a regex expression with a string variable?
You don't need to add /
at the beginning and the end of new RegExp(...)
and \
should be escaped as mentioned by anubhava :
var decimal = new RegExp("^\\s*(\\+|-)?((\\d+(" + myVar + "\\d+)?)|(" + myVar + "\\d+))\\s*$");
How to concat two javascript variables and regex expression
Try this (I use nodejs):
> var t1 = "Test1"
> var t2 = "Test2"
> var re = new RegExp('^' + t1 + '.*' + t2 + '$')
> re
/^Test1.*Test2$/
> re.test("Test1 this works Test2")
true
Note
.*
as stated in comments, this means any character repeated from 0 to ~- the slashes are automagically added when calling the
RegExp
constructor, but you can't have nested unprotected slashes delimiters - to ensure
Test1
is at the beginning, i put^
anchor, and forTest2
at the end, I added$
anchor - the regex constructor is not
ReGex
butRegExp
(note the trailingp
)
Is it Possible to Concatenate variable in Split Regexp in Javascript? Eg: var.split(/[A-Z]/+ variable + / \d/);
You can compile a regular expression from a variable, e.g.:
var regex = new RegExp();
var src = "\\s"; // don't forget to escape slashes!
var mods = "g";
regex.compile(src, mods);
alert(regex.source);
How can I concatenate regex literals in JavaScript?
Here is how to create a regular expression without using the regular expression literal syntax. This lets you do arbitary string manipulation before it becomes a regular expression object:
var segment_part = "some bit of the regexp";
var pattern = new RegExp("some regex segment" + /*comment here */
segment_part + /* that was defined just now */
"another segment");
If you have two regular expression literals, you can in fact concatenate them using this technique:var regex1 = /foo/g;
var regex2 = /bar/y;
var flags = (regex1.flags + regex2.flags).split("").sort().join("").replace(/(.)(?=.*\1)/g, "");
var regex3 = new RegExp(expression_one.source + expression_two.source, flags);
// regex3 is now /foobar/gy
It's just more wordy than just having expression one and two being literal strings instead of literal regular expressions. Properly escape variable inside RegEx (JavaScript)
You do not need /
and you can do without the capturing group:
var regex_string = "^\\w{" + highlight_chars_count + "}";
and thenreturn v.replace(regex, "<span>$&</span>");
^
Note that the regex delimiters (/.../
) are necessary when you declare a regex with a regex literal notation when a regex is static (e.g. var rx = /abc/g
). Here, you use a constructor notation.Also, $&
backreference refers to the whole match text, so, no need enclosing the whole pattern with a capturing group.
More information on RegExp
regex literal and constructor notation at MDN
How can i concatenate in javascript?
It looks like you're trying to use a variable in a regular expression literal. I don't think the interpreter would understand that. However, you can pass a string to the regular expression constructor, and strings can be concatenated/interpolated all you like.
For example:
var name = 'test';
var query = new RegExp('^ ' + name);
or:var name = 'test';
var query = new RegExp(`^ ${name}`);
Related Topics
Why Escape_JavaScript Before Rendering a Partial
Why Can't I Assign a New Value to "This" in a Prototype Function
JavaScript Switch VS. If...Else If...Else
Differencebetween Native Objects and Host Objects
Basic Ajax Send/Receive with Node.Js
Adding a Slide Effect to Bootstrap Dropdown
Load Local JSON File into Variable
Javascript: Dynamically Creating Variables for Loops
Backbone: Why Assign '$('#Footer')' to 'El'
JavaScript Replace() Method Dollar Signs
How to Chain These Functions Together with Promises
How to Change the Pop-Up Position of the Jquery Datepicker Control
How to Use a Link to Call JavaScript
How to Find a Reason Angularjs "Argument 'Myctrl' Is Not a Function, Got Undefined"
Write Elements into a Child Iframe Using JavaScript or Jquery
How to Load All Files in a Directory Using Webpack Without Require Statements