Prepend backslash to selected characters with regex [duplicate] - javascript

This question already has answers here:
Is there a RegExp.escape function in JavaScript?
(18 answers)
Closed 9 years ago.
The code I use at the moment is ugly because I have to write "replace" separately for every special character.
var str = ":''>";
str.replace("'","\\'").replace(">","\\>");
I would like to prepend backslash to < > * ( ) and ? through regex.

Using a regex that matches the characters with a character set, you could try:
str = str.replace(/([<>*()?])/g, "\\$1");
DEMO: http://jsfiddle.net/8ar3Z/
It matches any of the characters inside of the [ ] (the ones you specified), captures them with the surrounding () (so that it can be referenced as $1 in the replaced text part), and then prepends with \\.
UPDATE:
As a suggestion from Mr. #T.J.Crowder, it is unnecessary to capture with (), changing $1 to $&, written as:
str = str.replace(/[<>*()?]/g, "\\$&");
DEMO: http://jsfiddle.net/8ar3Z/1/
References:
Regex character set: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#special-character-set
$1 and $& use: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_string_as_a_parameter

Related

Replace a string containing special characters [duplicate]

This question already has answers here:
What special characters must be escaped in regular expressions?
(13 answers)
Closed 4 years ago.
Trying to replace a string that contains special characters. The purpose of this is to convert the query string into an understandable format for end users.
full string is:
var str = 'active=true^opened_by=6816f79cc0a8016401c5a33be04be441^ORassigned_to!=6816f79cc0a8016401c5a33be04be441^short_descriptionISNOTEMPTY^NQopened_atONToday#javascript:gs.beginningOfToday()#javascript:gs.endOfToday()^EQ';
Specifically the portion after ^NQ, in this example: opened_atONToday#javascript:gs.beginningOfToday()#javascript:gs.endOfToday(). I have split the original string with indexOf(^NQ) and passing the resulting sub-strings to a function. I'm then trying a .replace() as below:
var today = replacementString.replace(/(ONToday#javascript:gs.beginningOfToday()#javascript:gs.endOfToday())/g, ' is today ');
replacementString = today;
I have tried with various combinations of the above line, but have not returned what I am hoping for.
I've had no issues replacing special characters, or strings without special characters, but the combination of the 2 is confusing/frustrating me.
Any suggestions or guidance would be appreciated
You should escape the () to \(\) to match it literally or else it would mean a capturing group. For the match you could also omit the outer parenthesis and you have to escape the dot \. to match it literally.
ONToday#javascript:gs\.beginningOfToday\(\)#javascript:gs\.endOfToday\(\)
var str = 'active=true^opened_by=6816f79cc0a8016401c5a33be04be441^ORassigned_to!=6816f79cc0a8016401c5a33be04be441^short_descriptionISNOTEMPTY^NQopened_atONToday#javascript:gs.beginningOfToday()#javascript:gs.endOfToday()^EQ';
var today = str.replace(/ONToday#javascript:gs\.beginningOfToday\(\)#javascript:gs\.endOfToday\(\)/g, ' is today ');
replacementString = today;
console.log(today);

Javascript: Regex .test() for whitespace [duplicate]

This question already has answers here:
Why do regex constructors need to be double escaped?
(5 answers)
Closed 5 years ago.
Strange regex result when looking for any white space characters
new RegExp('^[^\s]+$').test('aaa');
=> true
That's expected, but then...
new RegExp('^[^\s]+$').test('aaa ');
=> true
How does that return true?
You need to escape \ in the string by \\. Otherwise, the generated regex would be /^[^s]+$/, which matches anything other than a string includes s.
new RegExp('^[^\\s]+$').test('aaa ');
Or you can use \S for matching anything other than whitespace.
new RegExp('^\\S+$').test('aaa ');
It would be better to use regex directly instead of parsing a regex string pattern.
/^[^\s]+$/.test('aaa ');
// or
/^\S+$/.test('aaa ');

Do I need to escape dash character in regex? [duplicate]

This question already has answers here:
Regex - Should hyphens be escaped? [duplicate]
(3 answers)
Closed 7 years ago.
I'm trying to understand dash character - needs to escape using backslash in regex?
Consider this:
var url = '/user/1234-username';
var pattern = /\/(\d+)\-/;
var match = pattern.exec(url);
var id = match[1]; // 1234
As you see in the above regex, I'm trying to extract the number of id from the url. Also I escaped - character in my regex using backslash \. But when I remove that backslash, still all fine ....! In other word, both of these are fine:
/\/(\d+)\-/
/\/(\d+)-/
Now I want to know, which one is correct (standard)? Do I need to escape dash character in regex?
You only need to escape the dash character if it could otherwise be interpreted as a range indicator (which can be the case inside a character class).
/-/ # matches "-"
/[a-z]/ # matches any letter in the range between ASCII a and ASCII z
/[a\-z]/ # matches "a", "-" or "z"
/[a-]/ # matches "a" or "-"
/[-z]/ # matches "-" or "z"
- may have a meaning only inside a character class [], so when you're outside of it you don't need to escape -

Replace pattern within string with space [duplicate]

This question already has answers here:
How do I replace all occurrences of a string in JavaScript?
(78 answers)
Closed 7 years ago.
I am getting long string with multiple occurances of pattern './.'. The string has dates as well in a format of dd.mm.yyyy.
First I tried with javascript replace method as:
str.replace('./.', ''). But it replaced only first occurance of './.'
Then I tried another regex which replaces special characters but it didn't work as it replaced '.' within dates as well.
How do I replace multiple occurances of a pattern './.' without affecting any other characters of a string ?
. is a special character in a regexp, it matches any character, you have to escape it.
str.replace(/\.\/\./g, '');
Use this simple pattern:
/\.\/\./g
to find all "./." strings in your text.
Try it :
str.replace(/\.\/\./g, '');
Escape . and d \
Add a g for global
Like this
str = str.replace(/\./\./g, '');

Why have two '\' in Regex? [duplicate]

This question already has answers here:
Why do regex constructors need to be double escaped?
(5 answers)
Extra backslash needed in PHP regexp pattern
(4 answers)
Regex to replace single backslashes, excluding those followed by certain chars
(3 answers)
Closed 7 years ago.
function trim(str) {
var trimer = new RegExp("(^[\\s\\t\\xa0\\u3000]+)|([\\u3000\\xa0\\s\\t]+\x24)", "g");
return String(str).replace(trimer, "");
}
why have two '\' before 's' and 't'?
and what's this "[\s\t\xa0\u3000]" mean?
You're using a literal string.
In a literal string, the \ character is used to escape some other chars, for example \n (a new line) or \" (a double quote), and it must be escaped itself as \\. So when you want your string to have \s, you must write \\s in your string literal.
Thankfully JavaScript provides a better solution, Regular expression literals:
var trimer = /(^[\s\t\xa0\u3000]+)|([\u3000\xa0\s\t]+\x24)/g
why have two '\' before 's' and 't'?
In regex the \ is an escape which tells regex that a special character follows. Because you are using it in a string literal you need to escape the \ with \.
and what's this "[\s\t\xa0\u3000]" mean?
It means to match one of the following characters:
\s white space.
\t tab character.
\xa0 non breaking space.
\u3000 wide space.
This function is inefficient because each time it is called it is converting a string to a regex and then it is compiling that regex. It would be more efficient to use a Regex literal not a string and compile the regex outside the function like the following:
var trimRegex = /(^[\s\t\xa0\u3000]+)|([\u3000\xa0\s\t]+$)/g;
function trim(str) {
return String(str).replace(trimRegex, "");
}
Further to this \s will match any whitespace which includes tabs, the wide space and the non breaking space so you could simplify the regex to the following:
var trimRegex = /(^\s+)|(\s+$)/g;
Browsers now implement a trim function so you can use this and use a polyfill for older browsers. See this Answer

Categories