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

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

Related

How to testing match escape characters in string? [duplicate]

This question already has answers here:
How can I use backslashes (\) in a string?
(4 answers)
Closed 3 years ago.
How to testing match escape characters in string?
What to need:
/^\888$/g.test('\888')
\888 = true
888 = false
console.log(/^888$/g.test('888'));
console.log(/^888$/g.test('\888'));
The backslash \ is reserved for use as an escape character in JavaScript.To use a backslash literally on your regex or any where for string operation, you need to use two backslashes e.g \\
That's why console.log('888' === '\888') returns true because '\8\8\8' is actually '888'
console.log('888' === '\888')
console.log('\888' === '\8\88')
You are escaping the first 8, you need to escape the \.
console.log(/^888$/g.test('888'));
console.log(/^888$/g.test('\\888'));

regex returning un expected value [duplicate]

This question already has an answer here:
Javascript RegEx Not Working [duplicate]
(1 answer)
Closed 5 years ago.
I expected new RegExp('\b\w{1,7}\b', "i").test('bc4rg6') to return true since I want to test of the string "bc4rg6" is alphanumeric and has from 1 to 7 characters. But the browser is giving false. How do I fix it so that I can test for the condition stated? Thanks
You need to escape the backslashes in the string, because \b is an escape sequence that turns into the backspace character.
console.log(new RegExp('\\b\\w{1,7}\\b', "i").test('bc4rg6'));
But if the regexp is a constant, you don't need to use new RegExp, just use a RegExp literal.
console.log(/\b\w{1,7}\b/i.test('bc4rg6'))
The RegExp function doesn't accept a string as an argument.
Instead pass a Regular Expression pattern with the escape slashes to indicate the start and end of the pattern.
new RegExp(/\b\w{1,7}\b/, "i").test('bc4rg6');
You can read more about the RegExp function at Mozilla.

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

Prepend backslash to selected characters with regex [duplicate]

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

Categories