javascript regex Numbers and letters only - javascript

This should automatically remove characters NOT on my regex, but if I put in the string asdf sd %$##$, it doesnt remove anything, and if I put in this #sdf%#, it only removes the first character. I'm trying to make it remove any and all instances of those symbols/special characters (anything not on my regex), but its not working all the time. Thanks for any help:
function ohno(){
var pattern = new RegExp("[^a-zA-Z0-9]+");
var str = "#sdf%#"; //"asdf sd %$##$" // Try both
str = str.replace(pattern,' ');
document.getElementById('msg').innerHTML = str;
}

You need the g flag to remove more than one match:
var pattern = new RegExp("[^a-zA-Z0-9]+", "g");
Note that it would be more efficient and readable to use a regex literal instead of the RegExp constructor:
var pattern = /[^a-zA-Z0-9]+/g;
reference

You need to set global using "g", The flag indicates that the regular expression should be tested against all possible matches in a string.
new RegExp("[^a-zA-Z0-9]+", "g")
Reference
var pattern = new RegExp("[^a-zA-Z0-9]+", "g");
var str = "#sdf%#"; //"asdf sd %$##$" // Try both
str = str.replace(pattern,' ');
alert(str)

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

Remove string between two variables

I have a string which has some data with a few special characters, Need to remove the data between the desired special char in JavaScript.
The special char would be obtained in a variable.
var desiredChar = "~0~";
And Imagine this to be the Input string:
~0~1|0|20170807|45|111.00|~0~~1~1|0|20170807|50|666.00|~1~~2~1|0|20170807|55|111.00|~2~
So I'm supposed to remove the text in bold.
The desired output is supposed to be-
~1~1|0|20170807|50|666.00|~1~~2~1|0|20170807|55|111.00|~2~
I've tried using "Replace" and "Regex", but as the desired character is being passed in a variable and keeps changing I'm facing difficulties.
You can create your own regex based on whatever the bounding character(s) are that contain the text you want removed, and then replace any text that matches that regex with a blank string "".
The JS below should work for your use case (and it should work for multiple occurrences as well):
var originalText = "~0~1|0|20170807|45|111.00|~0~~1~1|0|20170807|50|666.00|~1~~2~1|0|20170807|55|111.00|~2~";
var desiredChar = "~0~";
var customRegex = new RegExp(desiredChar + ".*?" + desiredChar, "gi");
var processedText = originalText.replace(customRegex, "");
console.log(processedText);
You can build your regex from the constructor with a string input.
var desiredChar = "~0~";
// use the g flag in your regex if you want to remove all substrings between desiredChar
var myRegex = new Regex(desiredChar + ".*" + desiredChar, 'ig');
var testString = "~0~1|0|20170807|45|111.00|~0~~1~1|0|20170807|50|666.00|~1~~2~1|0|20170807|55|111.00|~2~";
testString = testString.replace(myRegex, "");
Given input string you can use .indexOf(), .lastIndexOf() and .slice().
Note, OR character | passed to RegExp constructor should be escaped to avoid RegExp created by passing string interpreting | character as OR | within resulting RegExp passed to .replace().
var desiredChar = "~0~";
var str = "~0~1|0|20170807|45|111.00|~0~~1~1|0|20170807|50|666.00|~1~~2~1|0|20170807|55|111.00|~2~";
var not = str.slice(str.indexOf(desiredChar), str.lastIndexOf(desiredChar) + desiredChar.length);
// escape OR `|`
var res = str.replace(new RegExp(not.replace(/[|]/g, "\\|")), "");
console.log(res)
You can use the RegExp object:
var regexstring = "whatever";
var regexp = new RegExp(regexstring, "gi");
var str = "whateverTest";
var str2 = str.replace(regexp, "other");
document.write(str2);
Then you can construct regexstring in any way you want.
You can read more about it at http://www.regular-expressions.info/javascript.html

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.

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