regex returning un expected value [duplicate] - javascript

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.

Related

Defining regex in Javascript [duplicate]

This question already has answers here:
Why do regex constructors need to be double escaped?
(5 answers)
Closed 1 year ago.
I need to define below regex in Javascript:
(\bin region\b)(?!.*\1).+?(?=<)
I tried like below but it looks like not working:
var reg = new RegExp ('(\bin region\b)(?!.*\1).+?(?=<)');
Although the Atom tool matches the regex in the target string, JavaScript code is returning blank.
I am using this in Azure logic app (inline code executor connector)
Anyone can help me with this?
You can see it matches the text in Atom:
Inside a string you need to escape the backslashes.
Otherwise the backslash will escape the next character. So, writing \b will escape the character b instead use \\b which will escape the \
var reg = new RegExp ('(\\bin region\\b)(?!.*\\1).+?(?=<)');

In JavaScript, string '\m' is fully equals to string 'm', why? [duplicate]

This question already has answers here:
How can I use backslashes (\) in a string?
(4 answers)
Closed 2 years ago.
console.log('\d' === 'd'); // true
Character 'd' is not a special character, why javascript want to slice the escape notation.
It's better to keep the escape notation in my view.
When I want to fully match string-'\d' using regular expression, it just impossible!
Taking the following code as an example.
console.log(RE.test('\d')); // it should log true
console.log(RE.test('d')); // it should log false
Unfortunately, you just cannot figure out a regular expression pattern.
You have no reason to escape d in a string and JavaScript ignores it. If you need \d you need to escape the escape character: \\d.
See also Why do linters pick on useless escape character?
\d has a special meaning in regular expressions (a digit character), but also in strings (escaped 'd' character, which is exactly like 'd').
Any / creates an escape sequence in a string. Some are "useful" (\n === new line) and some arguably useless (`'\d' === 'd').
If you want the regex \d, you could
1 - use a regex literal instead : /\d/
2 - escape the \ in the string : '\\d', so that the string containing the two characters \ and d is correctly understood by Javascript.

Why this is an invalid regular expression? [duplicate]

This question already has answers here:
Regex created via new RegExp(myString) not working (backslashes)
(1 answer)
What is the difference between using "new RegExp" and using forward slash notation to create a regular expression?
(4 answers)
Why do regex constructors need to be double escaped?
(5 answers)
Closed 4 years ago.
I am trying to match all UK phone numbers in a string.
The pattern for this is:
^\(?(?:(?:0(?:0|11)\)?[\s-]?\(?|\+)44\)?[\s-]?\(?(?:0\)?[\s-]?\(?)?|0)(?:\d{2}\)?[\s-]?\d{4}[\s-]?\d{4}|\d{3}\)?[\s-]?\d{3}[\s-]?\d{3,4}|\d{4}\)?[\s-]?(?:\d{5}|\d{3}[\s-]?\d{3})|\d{5}\)?[\s-]?\d{4,5}|8(?:00[\s-]?11[\s-]?11|45[\s-]?46[\s-]?4\d))(?:(?:[\s-]?(?:x|ext\.?\s?|\#)\d+)?)$
But when I try to initiate a new RegExp like:
const myRegex = RegExp('^\(?(?:(?:0(?:0|11)\)?[\s-]?\(?|\+)44\)?[\s-]?\(?(?:0\)?[\s-]?\(?)?|0)(?:\d{2}\)?[\s-]?\d{4}[\s-]?\d{4}|\d{3}\)?[\s-]?\d{3}[\s-]?\d{3,4}|\d{4}\)?[\s-]?(?:\d{5}|\d{3}[\s-]?\d{3})|\d{5}\)?[\s-]?\d{4,5}|8(?:00[\s-]?11[\s-]?11|45[\s-]?46[\s-]?4\d))(?:(?:[\s-]?(?:x|ext\.?\s?|\#)\d+)?)$','g');
I get this error:
Uncaught SyntaxError: Invalid regular expression: /^(?(?:(?:0(?:0|11))?[s-]?(?|+)44)?[s-]?(?(?:0)?[s-]?(?)?|0)(?:d{2})?[s-]?d{4}[s-]?d{4}|d{3})?[s-]?d{3}[s-]?d{3,4}|d{4})?[s-]?(?:d{5}|d{3}[s-]?d{3})|d{5})?[s-]?d{4,5}|8(?:00[s-]?11[s-]?11|45[s-]?46[s-]?4d))(?:(?:[s-]?(?:x|ext.?s?|#)d+)?)$/: Invalid group
The error already shows you what the problem is. \ inside a string literal is the escape character. But escaping a character that doesn't need to be escaped simply "drops" the \:
console.log('\(');
So the value you are passing to the regular expression engine (and what the error shows you) is:
^(?(?...
(note: no backslash)
and (?( is not a valid character sequence in a regular expression.
You either have to
escape the escape characters ("\\(")
Use a regular expression literal instead of RegExp("string") (/^.../).

Why is the escape syntax different between two Javascript functions: search vs replace? [duplicate]

This question already has answers here:
JavaScript search() fails to find "()"
(2 answers)
Closed 6 years ago.
Use this string as example
s = "a(b"
These two work as expected
s.search("\\(")
1
s.replace("\(", "")
"ab"
But these don't
s.search("\(")
Uncaught SyntaxError: Invalid regular expression: /(/: Unterminated group
s.replace("\\(", "")
"a(b"
Huh? Why does search require one more escape than replace?
Also, shouldn't string input give a literal search, instead of being interpreted as a regexp? In theory, I shouldn't have to use escape characters at all.
The string literal '\(' is equivalent to '(', so you’re not really escaping anything at all with it.
String#search always interprets its argument as a regular expression; if you want to find an exact match, use String#indexOf.
> s.indexOf('(')
1
s.replace accepts either a string or a regular expression. You’re giving it the string ( in the first case (so it replaces the first opening parenthesis it sees) and \( in the second (not in the string, so it replaces nothing).

Regular expression seems to treat one string as multiple substrings [duplicate]

This question already has an answer here:
Reference - What does this regex mean?
(1 answer)
Closed 7 years ago.
Why the following code returns "ZZZCamelCase"?? Doesn't such regex examine if the string starts and ends with small case a-z? As what I understand, the str variable should match such condition, so the console output should be "ZZZZZZZZZZZZ", but obviously it somehow breaks the str, and examine the substring against the regex. Why? and how can I tell the program to treat "testCamelCase" as one string?
var str = "testCamelCase";
console.log(str.replace(/^[a-z]+/, 'Z')); // ZZZCamelCase
Here you are matching one or more lower case letters. That's going to be 'test' in your string, because after that comes an uppercase 'C'. So only 'test' gets rpelaced by 'ZZZ'
console.log(str.replace(/^[a-z]+/, 'ZZZ')); // ZZZCamelCase
Use
str.replace(/[a-z]/ig, 'Z')
to get 'ZZZZZZZZZZZZ'
You are forgetting, that regex is case sensitive. This means, that [a-z] doesn't capture the whole string. [a-zA-Z] does. So does [\w] including digits from 0-9.

Categories