Matching the string "/$" in a RegExp constructor [duplicate] - javascript

This question already has answers here:
Backslashes - Regular Expression - Javascript
(2 answers)
Closed 6 years ago.
I'm trying to match the phrase "/$" using the RegExp constructor, but no amount of escaping seems to help. Am is missing something?
RegExp("\/\$").test("/$")
// false
RegExp("/$").test("/$")
// false
RegExp("\/$").test("/$")
// false
RegExp("/\$").test("/$")
// false

You need to use \\ instead of \ and there is no need to escape / or use regex /\/\$/ directly. Check RegExp documentation for more info.
When using the constructor function, the normal string escape rules (preceding special characters with \ when included in a string) are necessary.
For example, /\w+/ is equivalent to new RegExp('\\w+')
console.log(
RegExp("/\\$").test("/$")
)
//or
console.log(
/\/\$/.test("/$")
)
Refer : Javascript regular expression - string to RegEx object

Related

same dynamic regex and inline regex not giving same output in javascript [duplicate]

This question already has answers here:
Backslashes - Regular Expression - Javascript
(2 answers)
Closed 7 years ago.
I have been staring at these two flavors of same regex and can't figure out why the outcome is different:
var projectName="SAMPLE_PROJECT",
fileName="1234_SAMPLE_PROJECT",
re1 = new RegExp('^(\d+)_SAMPLE_PROJECT$','gi'),
re2 = /^(\d+)_SAMPLE_PROJECT$/gi,
matches1 = re1.exec(fileName),
matches2 = re2.exec(fileName);
console.log(matches1);//returns null
console.log(matches2);//returns correctly
Here is the jsbin : https://jsbin.com/badoqokumu/edit?html,js,output
Any idea what I must be doing wrong with instantiating RegExp?
Thanks.
In the first case, you have a string literal, which uses \ to introduce escape sequences. \d in a string is just d. If you want \d, you need to type \\d instead.
In the second case, you have a regular expression literal, which does not interpret \ as a string escape sequence.

Why isn't the "or" operator being escaped in the Javascript regular expression [duplicate]

This question already has an answer here:
why is regex constructor not working? [duplicate]
(1 answer)
Closed 7 years ago.
I'm trying to check if there is a value between 'mystring' and the end character (which is a pipe). But
new RegExp('mystring:.+\|').test('bla')
Evaluates to true, even though I am escaping the '|' operator. What I was trying to achieve was this:
new RegExp('mystring:.+\|').test('mystring:|')
Evaluate to False (as nothing between 'mystring:' and the escaped '|'.
new RegExp('mystring:.+\|').test('mystring:something|')
Evaluate to True.
This isn't the behvaior I'm seeing as everything is evaluating to True and it doesn't look like the '|' is being escaped...
Escape the backslash. If " is used inside RegExp constructor then you must escape all the backslashes present inside the regex one more time.
new RegExp('mystring:.+\\|').test('mystring:something|')
or
new RegExp('mystring:.+[|]').test('mystring:something|')

JavaScript string.replace using "$$" outputs "$" [duplicate]

This question already has answers here:
`string.replace` weird behavior when using dollar sign ($) as replacement
(3 answers)
Closed 7 years ago.
Can anyone explain to me why JavaScript outputs a single $ when using $$ as the replace value?
"hi".replace("hi", "$$bye$$");
"hi".replace("hi", "\$\$bye\$\$");
//both output -> $bye$
//but I expected $$bye$$
The $ acts as a metacharacter in the replacement strings for that function. The string $$ is used to indicate that you just want a $. Otherwise, $ followed by a digit refers to the contents of a capturing group from the regular expression. As an example:
alert("aaabbb".replace(/(a+)(b+)/, "$2$1")); // bbbaaa
The string "\$\$bye\$\$" is exactly the same as the string "$$bye$$". Because $ is not a metacharacter in the string grammar, the backslash preceding it will be ignored.
You can double-up on the backslashes to have them survive the string constant parse, but the .replace() function will pay no particular attention do them, and you'll get \$\$ in the result.

Javascript regex ignoring backslash period requirement [duplicate]

This question already has answers here:
Why do regex constructors need to be double escaped?
(5 answers)
Closed 2 years ago.
For my regex:
^(http(s)?\://)?(([a-zA-Z]{1})|([a-zA-Z]{1}[a-zA-Z]{1})|([a-zA-Z]{1}[0-9]{1})|([0-9]{1}[a-zA-Z]{1})|([a-zA-Z0-9][a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]))\.([a-zA-Z]{2,6}|[a-zA-Z0-9-]{2,30}\.[a-zA-Z]{2,3})$
I am wondering as to why "john" passes? This regex is only supposed to pass for URLs
> var j = new RegExp("^(http(s)?\://)?(([a-zA-Z]{1})|([a-zA-Z]{1}[a-zA-Z]{1})|([a-zA-Z]{1}[0-9]{1})|([0-9]{1}[a-zA-Z]{1})|([a-zA-Z0-9][a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]))\.([a-zA-Z]{2,6}|[a-zA-Z0-9-]{2,30}\.[a-zA-Z]{2,3})$");
> j.test("john")
> true
There is a required \. within the regex line
You are constructing your regular expression by passing a string to the RegExp constructor function.
While \ has special meaning as an escape character in regular expressions, it also has a similar meaning in string literals.
The \\ in the string literal has been parsed into \ in the string and thus is treated as an escape character in the regular expression.
You need to provide an escaped \ and and escaped escape character.
So for a regular expression that matches a single \ you need:
var myRegEx = new RegExp("\\\\")
I suggest avoiding the constructor function and using a regex literal instead.
var myRegEx = /\\/;

How do I include an inline comment in a regular expression in JavaScript [duplicate]

This question already has answers here:
Commenting Regular Expressions
(7 answers)
Closed 3 years ago.
Inline comments works when a string passed to the RegExp constructor:
RegExp("foo"/*bar*/).test("foo")
but not with an expression. Is there any equivalent or alternative in JavaScript to emulate x-mode for the RegExp object?
Javascript supports neither the x modifier, nor inline comments (?#comment). See here.
I guess, the best you can do, is to use the RegExp constructor and write every line in e separate string and concatenate them (with comments between the strings):
RegExp(
"foo" + // match a foo
"bar" + // followed by a bar
"$" // at the end of the string
).test("somefoobar");
Other than using a zero-length sub-expression, it's not possible. Examples of "comments":
/[a-z](?!<-- Any letter)/
(?!..) is a negated look-ahead. It matches if the previous is not followed by the string within the parentheses. Since the thing between (?! and ) is a real regular (sub)expression, you cannot use arbitrary characters unless escaped with a backslash
An alternative is to use the positive look-ahead:
/[a-z](?=|<-- Any letter)/
This look-ahead will always match, because obviously the a-z is also followed by an empty string.

Categories

Resources