JavaScript Replace() Method Dollar Signs

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:



































PatternInserts
$$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.
$nWhere 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>").

How to replace multiple dollar ($) signs by pound signs in a Javascript MathJax text string?

simply use replaceAll() method

let s1 = "$$  \sin \theta $$"
, s2 = s1.replaceAll('$','£')
;
console.log ( s2 )

`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

How can I replace all occurrences of a dollar ($) with an underscore (_) in javascript?

The $ in RegExp is a special character, so you need to escape it with backslash.

new_str = str.replace(new RegExp('\\$', 'g'), '_');

however, in JS you can use the simpler syntax

new_str = str.replace(/\$/g, '_');

How to use replace method for dollar sign and comma?

using replace

const data = [
{
index: "14",
name: "Bob",
balance: "$1,000",
},
{
index: "23",
name: "John",
balance: "$1,200",
},
{
index: "17",
name: "Steve",
balance: "$8,000",
},
];
const result = data
.map((o) => parseFloat(o.balance.replace(/[$,]/g, "")))
.reduce((acc, curr) => acc + curr, 0);

console.log(result);

replacing a string with multiple $ symbol in javascript

The $ symbol has special meaning when used inside String.replace. You can escape it by doubling it:

var a = "xyz";a = a.replace("xyz", "$$$$$$");console.log(a)


Related Topics



Leave a reply



Submit