I can't replace properly with javascript and regex - javascript

I have this string:
var value = recordsArray_f006b490[]=1&recordsArray_9715b841[]=1&recordsArray_afb085e2[]=1&recordsArray_fc542e23[]=1&recordsArray_19490084[]=1&recordsArray_615a5055[]=1&recordsArray_32841aa6[]=1&recordsArray_a02a35c7[]=1&recordsArray_d32b5b88[]=1&recordsArray_d32d5339[]=1&recordsArray_56c2b8e10[]=1&recordsArray_8ce9f4211[]=1&recordsArray_5a87afc12[]=1&recordsArray_2b13c0113[]=1&recordsArray_afb085e14[]=1&recordsArray_51db9f216[]=1&recordsArray_2a7470415[]=1&recordsArray_d51057a17[]=1&recordsArray_b274ee918[]=1&recordsArray_d0812dd19[]=1&recordsArray_b1ede8920[]=1&recordsArray_9d76ae821[]=1&recordsArray_0ae779d22[]=1&recordsArray_871777923[]=1&recordsArray_9e22c9f24[]=220236&recordsArray_787c57e25[]=220236&recordsArray_499e25726[]=1&recordsArray_a0600da27[]=220236&recordsArray_9ef1fca28[]=220236&recordsArray_67eee1929[]=220236&recordsArray_24c3a0b30[]=220236&recordsArray_5d2090831[]=220236
And I want to replace "[]=" with "_" and I have the next javascript code:
var regex = new RegExp("[]=", "g");
alert(value.replace(regex, "_"));
but it doesnt change anything, how can I do it? Thanks!

Escape the first [ to indicate its not defining a character class;
var regex = new RegExp("\\[]=", "g");

Square brackets are reserved in regex. You need to escape them for matching
var regex = new RegExp("\\[\\]=", "g");

escape the brackets as they has special meaning.
var regex = new RegExp("\\[\\]=", "g");

As others have noted, you need to escape the square brackets, as they have special meaning in regex. I want to note, also, that the most clear and terse way to do this is with JavaScript's regex literal notation:
var regex = /\[]=/g;
You also only need to escape the opening [ bracket. Closing brackets (the ] character) only have a special meaning inside a character class, just as [ only has special meaning outside one.

You can't include brackets in regexp. Use \\[ for this.

Related

regex matching QUESTION MARK in url [duplicate]

This is a simple question I think.
I am trying to search for the occurrence of a string in another string using regex in JavaScript like so:
var content ="Hi, I like your Apartment. Could we schedule a viewing? My phone number is: ";
var gent = new RegExp("I like your Apartment. Could we schedule a viewing? My", "g");
if(content.search(gent) != -1){
alert('worked');
}
This doesn't work because of the ? character....I tried escaping it with \, but that doesn't work either. Is there another way to use ? literally instead of as a special character?
You need to escape it with two backslashes
\\?
See this for more details:
http://www.trans4mind.com/personal_development/JavaScript/Regular%20Expressions%20Simple%20Usage.htm
You should use double slash:
var regex = new RegExp("\\?", "g");
Why? because in JavaScript the \ is also used to escape characters in strings, so: "\?" becomes: "?"
And "\\?", becomes "\?"
You can delimit your regexp with slashes instead of quotes and then a single backslash to escape the question mark. Try this:
var gent = /I like your Apartment. Could we schedule a viewing\?/g;
Whenever you have a known pattern (i.e. you do not use a variable to build a RegExp), use literal regex notation where you only need to use single backslashes to escape special regex metacharacters:
var re = /I like your Apartment\. Could we schedule a viewing\?/g;
^^ ^^
Whenever you need to build a RegExp dynamically, use RegExp constructor notation where you MUST double backslashes for them to denote a literal backslash:
var questionmark_block = "\\?"; // A literal ?
var initial_subpattern = "I like your Apartment\\. Could we schedule a viewing"; // Note the dot must also be escaped to match a literal dot
var re = new RegExp(initial_subpattern + questionmark_block, "g");
And if you use the String.raw string literal you may use \ as is (see an example of using a template string literal where you may put variables into the regex pattern):
const questionmark_block = String.raw`\?`; // A literal ?
const initial_subpattern = "I like your Apartment\\. Could we schedule a viewing";
const re = new RegExp(`${initial_subpattern}${questionmark_block}`, 'g'); // Building pattern from two variables
console.log(re); // => /I like your Apartment\. Could we schedule a viewing\?/g
A must-read: RegExp: Description at MDN.

Javascript Replace, string with comma

I have a string that contains multiple occurrences of ],[ that I want to replace with ]#[
No matter what I try I cant get it right.
var find = '],[';
var regex = new RegExp(find, "g");
mytext.replace(regex, ']#[')
Doesn't work
mytext = mytext.replace(/],[/g,']#[');
Doesn't work
Any idea where I am going wrong?
The answer is that [ and ] are special characters in the context of regular expressions and as such need to be escaped either by means of \ i.e. to match ] you write [ when you use the convenient Javascript shorthand for regular expressions that you can find in the code below:
var regex= /\],\[/g
var result = mytext.replace(regex, ']#[')
Please check out the following jsFiddle: http://jsfiddle.net/JspRR/4/
As you can see the important bit is escaping the ] and the [ when constructing the regular expression.
Now if you did not want to use the Javascript regular expressions shorthand, you would still need to have the same escaping. However, in that case the \ character will need to be escaped itself ( ... by itself!)
var regex = new RegExp("\\],\\[", "g");
var result = mytext.replace(regex, ']#[')
The reason your example doesn't work is because normally square brackets represents a character class and therefore you need to escape them like so
var find = '\\],\\[';
var regex = new RegExp(find, "g");
mytext.replace(regex, ']#[')
You can also use a regex literal
mytext.replace(/\],\[/g, "]#[");
Try this:-
mytext.replace(/\],\[/g, ']#[')
Square brackets are special characters inside a regular expression: they are used to define a character set.
If you want to match square brackets in a regexp, you have to escape them, using back slash.
"[1],[2],[3]".replace(/\],\[/g, "]#[");
Or, in case you use the builtin constructor:
"[1],[2],[3]".replace(new RegExp("\\],\\[", "g"), "]#[");
In both case we have to use the g flag so that the regular expression can match all the occurrences of the searched string.
var str = "[1],[2],[3]";
console.log(str.replace(/\],\[/g, "]#["));
console.log(str.replace(new RegExp("\\],\\[", "g"), "]#["));
var str = "[1],[2],[3]";
var replaced = str.replace('],[', ']#[');

build Regex string with js

<script>
var String = "1 Apple and 13 Oranges";
var regex = /[^\d]/g;
var regObj = new RegExp(regex);
document.write(String.replace(regObj,''));
</script>
And it works fine - return all the digits in the string.
However when I put quote marks around the regex like this:
var regex = "/[^\d]/g"; This doesn't work.
How can I turn a string to a working regex in this case?
Thanks
You can create regular expressions in two ways, using the regular expression literal notation, or RegExp constructor. It seems you have mixed up the two. :)
Here is the literal way:
var regex = /[^\d]/g;
In this case you don't have use quotes. / characters at the ends serve as the delimiters, and you specify the flags at the end.
Here is how to use the RegExp constructor, in which you pass the pattern and flags (optional) as string. When you use strings you have to escape any special characters inside it using a '\'.
Since the '\' (backslash) is a special character, you have to escape the backslash using another backslash if you use double quotes.
var regex = new RegExp("[^\\d]", "g");
Hope this makes sense.
As slash(\) has special meaning for strings (e.g. "\n","\t", etc...), you need to escape that simbol, when you are passing to regexp:
var regex = "[^\\d]";
Also expression flags (e.g. g,i,etc...) must be passed as separate parameter for RegExp.
So overall:
var regex = "[^\\d]";
var flags = "g";
var regObj = new RegExp(regex, flags);

Easy Javascript Regex Question

Why doesn't this assign prepClass to the string selectorClass with underscores instead of non alpha chars? What do I need to change it to?
var regex = new RegExp("/W/", "g");
var prepClass = selectorClass.replace(regex, "_");
A couple of things:
If you use the RegExp constructor, you don't need the slashes, you are maybe confusing it with the syntax of RegExp literals.
You want match the \W character class.
The following will work:
var regex = new RegExp("\\W", "g");
The RegExp constructor accepts a string containing the pattern, note that you should double escape the slash, in order to get a single slash and a W ("\W") in the string.
Or you could simply use the literal notation:
var regex = /\W/g;
Recommended read:
Regular Expressions (MDC)

escaping question mark in regex javascript

This is a simple question I think.
I am trying to search for the occurrence of a string in another string using regex in JavaScript like so:
var content ="Hi, I like your Apartment. Could we schedule a viewing? My phone number is: ";
var gent = new RegExp("I like your Apartment. Could we schedule a viewing? My", "g");
if(content.search(gent) != -1){
alert('worked');
}
This doesn't work because of the ? character....I tried escaping it with \, but that doesn't work either. Is there another way to use ? literally instead of as a special character?
You need to escape it with two backslashes
\\?
See this for more details:
http://www.trans4mind.com/personal_development/JavaScript/Regular%20Expressions%20Simple%20Usage.htm
You should use double slash:
var regex = new RegExp("\\?", "g");
Why? because in JavaScript the \ is also used to escape characters in strings, so: "\?" becomes: "?"
And "\\?", becomes "\?"
You can delimit your regexp with slashes instead of quotes and then a single backslash to escape the question mark. Try this:
var gent = /I like your Apartment. Could we schedule a viewing\?/g;
Whenever you have a known pattern (i.e. you do not use a variable to build a RegExp), use literal regex notation where you only need to use single backslashes to escape special regex metacharacters:
var re = /I like your Apartment\. Could we schedule a viewing\?/g;
^^ ^^
Whenever you need to build a RegExp dynamically, use RegExp constructor notation where you MUST double backslashes for them to denote a literal backslash:
var questionmark_block = "\\?"; // A literal ?
var initial_subpattern = "I like your Apartment\\. Could we schedule a viewing"; // Note the dot must also be escaped to match a literal dot
var re = new RegExp(initial_subpattern + questionmark_block, "g");
And if you use the String.raw string literal you may use \ as is (see an example of using a template string literal where you may put variables into the regex pattern):
const questionmark_block = String.raw`\?`; // A literal ?
const initial_subpattern = "I like your Apartment\\. Could we schedule a viewing";
const re = new RegExp(`${initial_subpattern}${questionmark_block}`, 'g'); // Building pattern from two variables
console.log(re); // => /I like your Apartment\. Could we schedule a viewing\?/g
A must-read: RegExp: Description at MDN.

Categories

Resources