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.
Related
This question already has answers here:
What special characters must be escaped in regular expressions?
(13 answers)
Closed 2 years ago.
I have this sorta string = "^My Name Is Robert.^"
I want to remove the occurrences of ^ from this string. I tried the replace method like :
replyText.replace(/^/g, '');
But it hasn't any affect. Using the replace without the global works but only removes the first occurrence.
Should I just make a loop and keep looping the string with replace till no more '^' are contained, or is there a better way?
You need to escape the ^ character in RegEx:
replyText.replace(/\^/g, '');
The caret, ^, is a special character in Regex, therefore it has to be escaped with a backslash i.e
replyText.replace(/\^/g, '')
This question already has answers here:
JavaScript replace() method dollar signs
(6 answers)
Closed 3 years ago.
let str = '$$double_dollars$$'
console.log(str.replace('$$double_dollars$$', '$$no_double_dollars$$'));
// => $no_double_dollars$
// expected $$no_double_dollars$$
Why is this happening? How to work around this bug?
According to the MDN docs for String.prototype.replace (as what #Alex states), there is a list of special patterns which are evaluated accordingly and one of them is what you're using.
The special pattern is as follows:
$$ inserts a $
See the MDN docs for the full list of special patterns.
And as what #H.Figueiredo has commented, you can escape the dollar signs or follow one of the answers posted seconds after this answer.
See: MDN - String.prototype.replace # Specifying a function as a parameter
The replacement string can include the following special replacement patterns:
Pattern Inserts
$$ Inserts a "$".
$& Inserts the matched substring.
$` Inserts the portion of the string that precedes the matched substring.
$' Inserts the portion of the string that follows the matched substring.
$n Where n is a positive integer less than 100, inserts the nth parenthesized
submatch string, provided the first argument was a RegExp object.
Note that this is 1-indexed.
let str = '$$double_dollars$$'
console.log(str.replace('$$double_dollars$$', '$$$$yes_double_dollars$$$$'));
// => $$yes_double_dollars$$
See the documentation for passing a replacement String to replace.
$ is a special character. To express a literal $, use $$.
let str = '$$double_dollars$$'
console.log(str.replace('$$double_dollars$$', '$$$$result$$$$'));
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
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.
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.