Passing Parameter into function match - javascript

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

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

Regex: .exec() function not returning expected output

This doesn't return what I, or regex101, expects:
var myString = "Accel World|http://www.anime-planet.com/anime/accel-worldAh! My Goddess|http://www.anime-planet.com/anime/ah-my-goddess";
var reg = /[^|]*/g;
var regResponse = reg.exec(myString);
console.log(regResponse);
according to regex101, this should match everything except '|' and return it yet it only matches the first string, Accel World, as opposed to everything but '|'.
How do I fix this?
Exec will only return one result at a time (subsequent calls will return the rest, but you also need to use the + instead of *)
You could use the myString.match(reg) htough to get all results in one go.
var myString = "Accel World|http://www.anime-planet.com/anime/accel-worldAh! My Goddess|http://www.anime-planet.com/anime/ah-my-goddess";
var reg = /[^|]+/g;
var regResponse = myString.match(reg);
console.log(regResponse);
You need to loop .exec() to retrieve all matches. The documentation says
If your regular expression uses the "g" flag, you can use the exec()
method multiple times to find successive matches in the same string.
var reg = /[^|]+/g;
while(regResponse = reg.exec(myString)) {
console.log(regResponse);
}
Try a "+" instead of the "*"
So,
var reg = /[^|]+/g;

Match a string(input text from user) with regular expression

I have a requirement where there is a customet name text box and the user able to input customer name to search customer. And the condition is user can add do wild card search putting * either infront or after the customer name. And the customer name should be minimum three characters long. I am using Regex to validate the user entry.
Now in case the input is like "*aaa*" .. I am validate this type of input using the following regex :
[*]{1}([a-z]|[A-Z]|[0-9]){3,}[*]{1}
The code is like below:
var str = "*aaa*";
var patt = new RegExp("[*]{1}([a-z]|[A-Z]|[0-9]){3,}[*]{1}");
var res = patt.test(str);
alert(res);
var str = "*aaa***";
var patt = new RegExp("[*]{1}([a-z]|[A-Z]|[0-9]){3,}[*]{1}");
var res = patt.test(str);
alert(res);
var str = "*aaa*$$$$";
var patt = new RegExp("[*]{1}([a-z]|[A-Z]|[0-9]){3,}[*]{1}");
var res = patt.test(str);
alert(res);
Now for the input "*aaa*" res is coming true. But for this type of inputs also "*aaa**", "*aaa*$" its comimg true. And this expected as these expressions also contains the part( *aaa*) which satisfies the regex.But these inputs("*aaa**", *aaa*$** etc. ) are wrong.
Please let me know where I am doing wrong ? is there any issue with the regex or the way checking is wrong ?
^(?:[*]([a-z]|[A-Z]|[0-9]){3,}[*])$
Use anchors ^$ to disable partial matching.See demo.
https://regex101.com/r/tS1hW2/17
The string *aaa*$$$ contains a segment of *aaa*, so it will yield true; to match against the whole string you need to add anchors on both sides. The $ and ^ anchors assert the start and end of the subject respectively.
Also, you can simply the expression greatly by using a character class trick. The \w is comprised of [0-9a-zA-Z_], and we only don't want the underscore, so we can use a negative character class with the opposite of \w (which is \W) and an underscore; I agree, it takes some mental power ;-)
var str = "*aaa*$";
var patt = /^\*[^\W_]{3,}\*$/;
var res = patt.test(str);
alert(res); // false
Alternatively, you can merge all your character classes together into one like so:
[A-Za-z0-9]

Regex working fine in C# but not in Javascript

I have the following javascript code:
var markdown = "I have \(x=1\) and \(y=2\) and even \[z=3\]"
var latexRegex = new RegExp("\\\[.*\\\]|\\\(.*\\\)");
var matches = latexRegex.exec(markdown);
alert(matches[0]);
matches has only matches[0] = "x=1 and y=2" and should be:
matches[0] = "\(x=1\)"
matches[1] = "\(y=2\)"
matches[2] = "\[z=3\]"
But this regex works fine in C#.
Any idea why this happens?
Thank You,
Miguel
Specify g flag to match multiple times.
Use String.match instead of RegExp.exec.
Using regular expression literal (/.../), you don't need to escape \.
* matches greedily. Use non-greedy version: *?
var markdown = "I have \(x=1\) and \(y=2\) and even \[z=3\]"
var latexRegex = /\[.*?\]|\(.*?\)/g;
var matches = markdown.match(latexRegex);
matches // => ["(x=1)", "(y=2)", "[z=3]"]
Try non-greedy: \\\[.*?\\\]|\\\(.*?\\\). You need to also use a loop if using the .exec() method like so:
var res, matches = [], string = 'I have \(x=1\) and \(y=2\) and even \[z=3\]';
var exp = new RegExp('\\\[.*?\\\]|\\\(.*?\\\)', 'g');
while (res = exp.exec(string)) {
matches.push(res[0]);
}
console.log(matches);
Try using the match function instead of the exec function. exec only returns the first string it finds, match returns them all, if the global flag is set.
var markdown = "I have \(x=1\) and \(y=2\) and even \[z=3\]";
var latexRegex = new RegExp("\\\[.*\\\]|\\\(.*\\\)", "g");
var matches = markdown.match(latexRegex);
alert(matches[0]);
alert(matches[1]);
If you don't want to get \(x=1\) and \(y=2\) as a match, you will need to use non-greedy operators (*?) instead of greedy operators (*). Your RegExp will become:
var latexRegex = new RegExp("\\\[.*?\\\]|\\\(.*?\\\)");

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:

Categories

Resources