2

i tried to replace a string, provided the string regex with a value that has $ in the end. enter image description here

Can anyone tell me what is happening in

Looking into mdn string replace docs, i found it is expected.

But what should one do he want to ignore this. Means i want the replacing value should get as it is replaced, with 4 $s here.

4
  • hint: you can observe in your first attempt itself that $ in output is half the number you have given in pattern Commented Jan 15, 2016 at 9:28
  • what should one do he want to ignore this. - You cannot, as this is one of the language features. Commented Jan 15, 2016 at 9:29
  • From the reference you linked in the question, the first pattern itself says -- $$ Inserts a "$". Commented Jan 15, 2016 at 9:30
  • okay, but how can we develop a JS system, where client inputs a replacing string and also the replacement value in string. Should we teach client to put double $s in the end? Commented Jan 15, 2016 at 9:34

1 Answer 1

4

You need to double the dollars in the replacement pattern as $$ are actually $.

.replace(/{{one}}/g, '000$$$$$$$$')

See String#replace help:

Pattern      Inserts
$$            Inserts a "$".

If a user types $ in the replacement (that is, in case it is user-defined) you can just double it:

var ptrn = "{{one}}"; // regex pattern from user input
var repl = "000$$$$"; // replacement from user input
var rx = RegExp(ptrn, "g"); // building a dynamic regex
document.write("pp{{one}}pp".replace(rx, repl.replace(/\$/g, '$$$$')));
//                                            ^--- doubling $s-----^

Sign up to request clarification or add additional context in comments.

2 Comments

okay, but how can we develop a JS system, where client inputs a replacing string and also the replacement value in string. Should we teach client to put double $s in the end?
hmm.. thats cool, i had that in my mind just a second before.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.