Javascript RegExp string pattern - javascript

I need to check JS matches for a dynamically generated string.
ie.
for(i=0; i< arr.length; i++)
{
pattern_1="/part of "+arr[i]+" string!/i";
if( string.search(pattern_1) != -1)
arr_num[i]++;
}
However, this code doesn't work - I presume due to the quotes. How do I do this?
Many thanks.

The /pattern/ literal only works as, well, a literal. Not within a string.
If you want to use a string pattern to create a regular expression, you need to create a new RegExp object:
var re = new RegExp(pattern_1)
And in that case, you would omit the enclosing frontslashes (/). These two lines are equivalent:
var re = /abc/g;
var re = new RegExp("abc", "g");

Try this:
// note you dont need those "/" and that "i" modifier is sent as second argument
pattern_1= new RegExp("part of "+arr[i]+" string!", "i");

The problem is that you are passing a string to the search function so it treats it as a string. Try using a RegExp object like so:
myregexp = new RegExp("part of " + arr[i] + " string!", "i")
if (string.search(myregexp) != -1) {
arr_num[i]++;
}

Related

How to put a variable in my JS regular expression? [duplicate]

I want to add a (variable) tag to values with regex, the pattern works fine with PHP but I have troubles implementing it into JavaScript.
The pattern is (value is the variable):
/(?!(?:[^<]+>|[^>]+<\/a>))\b(value)\b/is
I escaped the backslashes:
var str = $("#div").html();
var regex = "/(?!(?:[^<]+>|[^>]+<\\/a>))\\b(" + value + ")\\b/is";
$("#div").html(str.replace(regex, "" + value + ""));
But this seem not to be right, I logged the pattern and its exactly what it should be.
Any ideas?
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.
If you are trying to use a variable value in the expression, you must use the RegExp "constructor".
var regex = "(?!(?:[^<]+>|[^>]+<\/a>))\b(" + value + ")\b";
new RegExp(regex, "is")
I found I had to double slash the \b to get it working. For example to remove "1x" words from a string using a variable, I needed to use:
str = "1x";
var regex = new RegExp("\\b"+str+"\\b","g"); // same as inv.replace(/\b1x\b/g, "")
inv=inv.replace(regex, "");
You don't need the " to define a regular expression so just:
var regex = /(?!(?:[^<]+>|[^>]+<\/a>))\b(value)\b/is; // this is valid syntax
If value is a variable and you want a dynamic regular expression then you can't use this notation; use the alternative notation.
String.replace also accepts strings as input, so you can do "fox".replace("fox", "bear");
Alternative:
var regex = new RegExp("/(?!(?:[^<]+>|[^>]+<\/a>))\b(value)\b/", "is");
var regex = new RegExp("/(?!(?:[^<]+>|[^>]+<\/a>))\b(" + value + ")\b/", "is");
var regex = new RegExp("/(?!(?:[^<]+>|[^>]+<\/a>))\b(.*?)\b/", "is");
Keep in mind that if value contains regular expressions characters like (, [ and ? you will need to escape them.
I found this thread useful - so I thought I would add the answer to my own problem.
I wanted to edit a database configuration file (datastax cassandra) from a node application in javascript and for one of the settings in the file I needed to match on a string and then replace the line following it.
This was my solution.
dse_cassandra_yaml='/etc/dse/cassandra/cassandra.yaml'
// a) find the searchString and grab all text on the following line to it
// b) replace all next line text with a newString supplied to function
// note - leaves searchString text untouched
function replaceStringNextLine(file, searchString, newString) {
fs.readFile(file, 'utf-8', function(err, data){
if (err) throw err;
// need to use double escape '\\' when putting regex in strings !
var re = "\\s+(\\-\\s(.*)?)(?:\\s|$)";
var myRegExp = new RegExp(searchString + re, "g");
var match = myRegExp.exec(data);
var replaceThis = match[1];
var writeString = data.replace(replaceThis, newString);
fs.writeFile(file, writeString, 'utf-8', function (err) {
if (err) throw err;
console.log(file + ' updated');
});
});
}
searchString = "data_file_directories:"
newString = "- /mnt/cassandra/data"
replaceStringNextLine(dse_cassandra_yaml, searchString, newString );
After running, it will change the existing data directory setting to the new one:
config file before:
data_file_directories:
- /var/lib/cassandra/data
config file after:
data_file_directories:
- /mnt/cassandra/data
Much easier way: use template literals.
var variable = 'foo'
var expression = `.*${variable}.*`
var re = new RegExp(expression, 'g')
re.test('fdjklsffoodjkslfd') // true
re.test('fdjklsfdjkslfd') // false
Using string variable(s) content as part of a more complex composed regex expression (es6|ts)
This example will replace all urls using my-domain.com to my-other-domain (both are variables).
You can do dynamic regexs by combining string values and other regex expressions within a raw string template. Using String.raw will prevent javascript from escaping any character within your string values.
// Strings with some data
const domainStr = 'my-domain.com'
const newDomain = 'my-other-domain.com'
// Make sure your string is regex friendly
// This will replace dots for '\'.
const regexUrl = /\./gm;
const substr = `\\\.`;
const domain = domainStr.replace(regexUrl, substr);
// domain is a regex friendly string: 'my-domain\.com'
console.log('Regex expresion for domain', domain)
// HERE!!! You can 'assemble a complex regex using string pieces.
const re = new RegExp( String.raw `([\'|\"]https:\/\/)(${domain})(\S+[\'|\"])`, 'gm');
// now I'll use the regex expression groups to replace the domain
const domainSubst = `$1${newDomain}$3`;
// const page contains all the html text
const result = page.replace(re, domainSubst);
note: Don't forget to use regex101.com to create, test and export REGEX code.
var string = "Hi welcome to stack overflow"
var toSearch = "stack"
//case insensitive search
var result = string.search(new RegExp(toSearch, "i")) > 0 ? 'Matched' : 'notMatched'
https://jsfiddle.net/9f0mb6Lz/
Hope this helps

JavaScript regex: replace variables of whole string in a sentence [duplicate]

How to create regex pattern which is concatenate with variable, something like this:
var test ="52";
var re = new RegExp("/\b"+test+"\b/");
alert('51,52,53'.match(re));
Thanks
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.)
With ES2015 (aka ES6) you can use template literals when constructing RegExp:
let test = '53'
const regexp = new RegExp(`\\b${test}\\b`, 'gi') // showing how to pass optional flags
console.log('51, 52, 53, 54'.match(regexp))
you can use
/(^|,)52(,|$)/.test('51,52,53')
but i suggest to use
var list = '51,52,53';
function test2(list, test){
return !((","+list+",").indexOf(","+test+",") === -1)
}
alert( test2(list,52) )

Javascript regexp exec doesn't work

Recently I posted a question about time format conversion via regular expressions in JS.
Now I modified the code a bit.
function getHours(value) {
if (value == 0)
return 0;
var re = new RegExp("^(?=\d)((\d+)(h|:))?\s*((\d+)m?)?$", "g");
var myArray = re.exec(value);
var hours = 0;
var minutes = 0;
if (myArray != null) {
if (myArray[2] != null) {
hours = myArray[2];
}
if (myArray[5] != null) {
minutes = myArray[5];
}
}
return Number(hours) + Number(minutes) / 60;
}
The problem is that it returns a null value in myArray.
As I'm new to JS, I couldn't solve this problem. What am I doing wrong?
The problem is here
new RegExp("^(?=\d)((\d+)(h|:))?\s*((\d+)m?)?$", "g");
When you create a new Regular Expression through the constructor, you provide strings. In string literals, the backslash character (\) means ‘escape the next character’.
You have to escape those backslashes, so they won't escape their subsequent character. So the correct version is:
new RegExp("^(?=\\d)((\\d+)(h|:))?\\s*((\\d+)m?)?$", "g");
See this article on values, variables, and literals from MDN for more information on escaping characters in JavaScript.
Problem is in this line:
var re = new RegExp("^(?=\d)((\d+)(h|:))?\s*((\d+)m?)?$", "g");
Pls understand that RegExp class takes a String as argument to construct and you need to double escape \d and \s to be correctly interpreted by RegEx engine so \d should become \\d and \s should become \\sin your regex String like this:
var re = new RegExp("^(?=\\d)((\\d+)(h|:))?\\s*((\\d+)m?)?$", "g");
Note that you can also do:
var re = /^(?=\d)((\d+)(h|:))?\s*((\d+)m?)?$/g;
I changed exec call like this:
var myArray = (/^(?=\d)((\d+)(h|:))?\s*((\d+)m?)?$/g).exec(value);
And it worked! Can anyone explain the difference?

how to config RegExp when string contains parentheses

I'm sure this is an easy one, but I can't find it on the net.
This code:
var new_html = "foo and bar(arg)";
var bad_string = "bar(arg)";
var regex = new RegExp(bad_string, "igm");
var bad_start = new_html.search(regex);
sets bad_start to -1 (not found). If I remove the (arg), it runs as expected (bad_start == 8). Is there something I can do to make the (very handy) "new Regexp" syntax work, or do I have to find another way? This example is trivial, but in the real app it would be doing global search and replace, so I need the regex and the "g". Or do I?
TIA
Escape the brackets by double back slashes \\. Try this.
var new_html = "foo and bar(arg)";
var bad_string = "bar\\(arg\\)";
var regex = new RegExp(bad_string, "igm");
var bad_start = new_html.search(regex);
Demo
Your RegEx definition string should be:
var bad_string = "bar\\(arg\\)";
Special characters need to be escaped when using RegEx, and because you are building the RegEx in a string you need to escape your escape character :P
http://www.regular-expressions.info/characters.html
You need to escape the special characters contained in string you are creating your Regex from. For example, define this function:
function escapeRegex(string) {
return string.replace(/[/\-\\^$*+?.()|[\]{}]/g, '\\$&');
}
And use it to assign the result to your bad_string variable:
let bad_string = "bar(arg)"
bad_string = escapeRegex(bad_string)
// You can now use the string to create the Regex :v:

how do I capture something after something else? like a referer=someString

I have ref=Apple
and my current regex is
var regex = /ref=(.+)/;
var ref = regex.exec(window.location.href);
alert(ref[0]);
but that includes the ref=
now, I also want to stop capturing characters if a & is at the end of the ref param. cause ref may not always be the last param in the url.
You'll want to split the url parameters, rather than using a regular expression.
Something like:
var get = window.location.href.split('?')[1];
var params = get.split('&');
for (p in params) {
var key = params[p].split('=')[0];
var value = params[p].split('=')[1];
if (key == 'ref') {
alert('ref is ' + value);
}
}
Use ref[1] instead.
This accesses what is captured by group 1 in your pattern.
Note that there's almost certainly a better way to do key/value parsing in Javascript than regex.
References
regular-expressions.info/Brackets for Capturing
You are using the ref wrong, you should use ref[1] for the (.+), ref[0] is the whole match.
If & is at the end, modify the regexp to /ref=([^&]+)/, to exclude &s.
Also, make sure you urldecode (unescape in JavaScript) the match.
Capture only word characters and numbers:
var regex = /ref=(\w+)/;
var ref = regex.exec(window.location.href);
alert(ref[1]);
Capture word characters, numbers, - and _:
var regex = /ref=([\w_\-]+)/;
var ref = regex.exec(window.location.href);
alert(ref[1]);
More information about Regular Expressions (the basics)
try this regex pattern ref=(.*?)&
This pattern will match anything after ref= and stop before '&'
To get the value of m just use following code:
var regex = /ref=(.*?)&/;
var ref = regex.exec(window.location.href);
alert(ref[1]);

Categories

Resources