how to config RegExp when string contains parentheses - javascript

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:

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

Use regex to remove "public://" from string

Im lost in part of this.
I want to remove the public:// in every link of an image like public://china-taxi_4.jpg
I have tried this but returns null:
var _img = 'public://china-taxi_4.jpg';
var regex = /(public:)(\/\w+)/;
var matches = _img.match(regex);
console.log(matches);
Hope you can help.
I want to remove the 'public://' in every link of an image.
> var img = 'public://china-taxi_4.jpg';
> img.replace(/public:\/\/(?=\S+?\.jpg(?:\s|$))/, "")
'china-taxi_4.jpg'
It removes the word public:// only in the strings which ends with .jpg
You are removing a literal string, not a regular expression. So try:
var _img = 'public://china-taxi_4.jpg';
var result = _img.replace("public://","");
console.log(result);
Regexes are for matching complex expressions.
I think you're missing a slash, try:
var _img = 'public://china-taxi_4.jpg';
var regex = /(public:)(\/\/\w+)/;
var matches = _img.match(regex);
console.log(matches);
From Mozilla Developer Network String.prototype.replace():
Example: Defining the regular expression in replace()
In the following example, the regular expression is defined in
replace() and includes the ignore case flag.
var str = 'Twas the night before Xmas...';
var newstr = str.replace(/xmas/i, 'Christmas');
console.log(newstr);
This prints:
'Twas the night before Christmas...'
To match the beginning of a string, use ^
To escape characters that have special meaning in regexp like : and / so that regexp will match these literally, prepend \
This suggests:
var _img = 'public://china-taxi_4.jpg';
var newimg = _img.replace(/^public\:\/\//i, '');
Tested and working in chrome browser console window.
Note: This answer also matches an earlier comment by #dystroy, so I have marked it CW.
var re = /(public:)(\/\/[\w-.]+)/g;
See demo.
http://regex101.com/r/rA7aS3/9

Passing Parameter into function match

I am using the function match for a search engine, so whenever a user types a search-string I take that string and use the match function on an array containing country names, but it doesn't seem to work.
For example if I do :
var string = "algeria";
var res = string.match(/alge/g); //alge is what the user would have typed in the search bar
alert(res);
I get a string res = "alge": //thus verifying that alge exists in algeria
But if I do this, it returns null, why? and how can I make it work?
var regex = "/alge/g";
var string = "algeria";
var res = string.match(regex);
alert(res);
To make a regex from a string, you need to create a RegExp object:
var regex = new RegExp("alge", "g");
(Beware that unless your users will be typing actual regular expressions, you'll need to escape any characters that have special meaning within regular expressions - see Is there a RegExp.escape function in Javascript? for ways to do this.)
You don't need quotes around the regex:
var regex = /alge/g;
Remove the quotes around the regex.
var regex = /alge/g;
var string = "algeria";
var res = string.match(regex);
alert(res);
found the answer, the match function takes a regex object so have to do
var regex = new RegExp(string, "g");
var res = text.match(regex);
This works fine

Javascript regexp does not work

Test string is "page-42440233_45778105"
pattern "(page-\d+_\d+)"
Online tester(http://www.regexr.com/) successfuly finded mathc,but in browser js result is null. Why?
var re = new RegExp("(page-\d+_\d+)", "gim");
var r_array = message.match(re);
console.log(r_array);
I think this would be a better pattern
var re = /^page-\d+_\d+$/i;
It also matches the beginning (^) and end ($) of the string
message.match(re);
//=> ["page-42440233_45778105"]
You need to escape \ if you use string literal:
var message = "page-42440233_45778105";
var re = new RegExp("(page-\\d+_\\d+)", "gim");
var r_array = message.match(re);
console.log(r_array);
// => ["page-42440233_45778105"]
More preferably, use regular expression literal:
var re = /(page-\d+_\d+)/gim;
When you use a string literal, you must escape the \ :
var re = new RegExp("(page-\\d+_\\d+)", "gim");
A better solution here would be to use a regex literal :
var re = /(page-\d+_\d+)/gim
Don't use the RegExp constructor if the regular expression is constant, regex literals are much more convenient.

how to extract string part and ignore number in jquery?

I have a string like foobar1, foobaz2, barbar23, nobar100 I want only foobar, foobaz, barbar, nobar and ignoring the number part.
If you want to strip out things that are digits, a regex can do that for you:
var s = "foobar1";
s = s.replace(/\d/g, "");
alert(s);
// "foobar"
(\d is the regex class for "digit". We're replacing them with nothing.)
Note that as given, it will remove any digit anywhere in the string.
This can be done in JavaScript:
/^[^\d]+/.exec("foobar1")[0]
This will return all characters from the beginning of string until a number is found.
var str = 'foobar1, foobaz2, barbar23, nobar100';
console.log(str.replace(/\d/g, ''));
Find some more information about regular expressions in javascript...
This should do what you want:
var re = /[0-9]*/g;
var newvalue= oldvalue.replace(re,"");
This replaces al numbers in the entire string. If you only want to remove at the end then use this:
var re = /[0-9]*$/g;
I don't know how to do that in JQuery, but in JavaScript you can just use a regular expression string replace.
var yourString = "foobar1, foobaz2, barbar23, nobar100";
var yourStringMinusDigits = yourString.replace(/\d/g,"");

Categories

Resources