Javascript Replace, string with comma - javascript

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('],[', ']#[');

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.

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);

I can't replace properly with javascript and regex

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.

Match dynamic string using regex

I'm trying to detect an occurrence of a string within string. But the code below always returns "null". Obviously something went wrong, but since I'm a newbie, I can't spot it. I'm expecting that the code returns "true" instead of "null"
var searchStr = 'width';
var strRegExPattern = '/'+searchStr+'\b/';
"32:width: 900px;".match(new RegExp(strRegExPattern,'g'));
Please don't put '/' when you pass string in RegExp option
Following would be fine
var strRegExPattern = '\\b'+searchStr+'\\b';
"32:width: 900px;".match(new RegExp(strRegExPattern,'g'));
You're mixing up the two ways of creating regexes in JavaScript. If you use a regex literal, / is the regex delimiter, the g modifier immediately follows the closing delimiter, and \b is the escape sequence for a word boundary:
var regex = /width\b/g;
If you create it in the form of a string literal for the RegExp constructor, you leave off the regex delimiters, you pass modifiers in the form of a second string argument, and you have to double the backslashes in regex escape sequences:
var regex = new RegExp('width\\b', 'g');
The way you're doing it, the \b is being converted to a backspace character before it reaches the regex compiler; you have to escape the backslash to get it past JavaScript's string-literal escape-sequence processing. Or use a regex literal.
The right tool for this job is not regex, but String.indexOf:
var str = '32:width: 900px;',
search = 'width',
isInString = !(str.indexOf(search) == -1);
// isInString will be a boolean. true in this case
Documentation: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/String/indexOf
Notice that '\\b' is a single slash in a string followed by the letter 'b', '\b' is the escape code \b, which doesn't exist, and collapses to 'b'.
Also consider escaping metacharacters in the string if you intend them to only match their literal values.
var string = 'width';
var quotemeta_string = string.replace(/[^$\[\]+*?.(){}\\|]/g, '\\$1'); // escape meta chars
var pattern = quotemeta_string + '\\b';
var re = new RegExp(pattern);
var bool_match = re.test(input); // just test whether matches
var list_matches = input.match(re); // get captured results
You can use back tick symbol to make your string dynamic "`".
var colName = 'Col1';
var result = strTest.match(`xxxxxxx${colName}`);
by injecting ${colName} in to the text, it can be editable dynamically.

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