`string.replace` weird behavior when using dollar sign ($) as replacement
In order to use $
in resulting string, use $$
as $
has special meaning in JavaScript Regular Expressions and String replace
method: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_string_as_a_parameter
JavaScript replace() method dollar signs
It’s because $$
inserts a literal "$
".
So, you need to use:
a = "aman/gupta";
a = a.replace("/", "$$$$"); // "aman$$gupta"
See the following special 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 non-negative integer less than 100, inserts the _n_th parenthesized submatch string, provided the first argument was a RegExp object. |
$< Name> | Where Name is a capturing group name. If the group is not in the match, or not in the regular expression, or if a string was passed as the first argument to replace instead of a regular expression, this resolves to a literal (e.g., "$<Name> "). |
escaping $ sign for String.replace
As it states in String.prototype.replace(). To escape '$' in replacement content, you should use '$$' instead of '\$'.
So a proper way of constructing it would be
'{0}'.replace('{0}',
'categories.Country === \'$formData.lossLocation.state$\'.toUpperCase()'
.replace(/\$/g, '$$$$')
)
Dollar sign replacement not working Java
\u0024
is the Unicode escape sequence for the dollar sign. Your code is checking for the dollar sign (w.charAt(0) == '$'
), removing it (w = w.replace("\u0024", "")
), then putting it back again ('\u0024' + i
).
Edit: I knew this was strange, but I missed the actual problem. I see now; Matcher.appendReplacement is complaining because there is a $+number sequence in the replacement, and is treating it as a reference to a captured group.
This is because \u0024
does not escape anything as far as appendReplacement is concerned, because that escape sequence is parsed at compile time. By run time, a string written in the source as "\u0024"
has length 1, and its only character is a literal dollar sign. (In fact, Unicode escape sequences are almost the first thing parsed by the Java compiler, right after counting lines. For example, you can declare a variable int $foo;
and then use it in code (outside of regexes or even strings) with \u0024foo = 123;
(or \u0024\u0066\u006f\u006f = 123;
)).
To escape a dollar sign for appendReplacement, escape it with a backslash. Because escape sequences in strings are parsed at compile time, you must also escape the backslash. I.e.,
m.appendReplacement(sb, ChatTweaks.Citrus.get("dollarIn") + "\\$" + i);
To clarify, at compile time, the compiler sees "\\$"
and creates a string of length 2; whose characters are \ and $. At run time, appendReplacement can see them and insert just a $.
The method Matcher.quoteReplacement can also do this for you, which is a good idea in case ChatTweaks.Citrus.get("dollarIn")
could also return any dollar signs that it's not supposed to and which would also upset the matcher. E.g.,
m.appendReplacement(sb,
Matcher.quoteReplacement(ChatTweaks.Citrus.get("dollarIn") + "$" + i));
Can not replace ? by $', it so weird
You need to use $$'
if you want replace to $'
because $'
is a special replacement pattern that
Inserts the portion of the string that follows the matched substring.
All the available patterns are:
$$ 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 or $nn: Where n or nn are decimal digits, inserts the nth parenthesized submatch string, provided the first argument was a RegExp object.
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/replace
JavaScript string.replace using $$ outputs $
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 Topics
Generating Non-Repeating Random Numbers in Js
Understanding Meteor Publish/Subscribe
How to Use Revealing Module Pattern in JavaScript
What's the Cause of the Error 'Getaddrinfo Eai_Again'
What Does $(Function() {} ); Do
Javascript: Which Browsers Support Parsing of Iso-8601 Date String with Date.Parse
How to Convert the "Arguments" Object to an Array in JavaScript
How to Conditionally Import an Es6 Module
Cloud Firestore Case Insensitive Sorting Using Query
How to Set Time Delay in JavaScript
How to Load Local Script Files as Fallback in Cases Where Cdn Are Blocked/Unavailable
Sending Credentials with Cross-Domain Posts
Is the Promise Constructor Callback Executed Asynchronously
Angularjs - How to Use $Routeparams in Generating the Templateurl
How to Get Visitor's Location (I.E. Country) Using Geolocation
JavaScript - How to Extract Filename from a File Input Control