Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

using replace() to replace the dollar sing '$' from a string

Firstly see below code:

var givenString = 'This is  a $ample $tring to be $ome Random $egment$ in $ociety'
console.log(givenString.replace(/$/g,"S")

This won’t throw an output as expected i.e This is a Sample String to be Some Random SegmentS in Society

I tried placing the pattern in variable to run it but didn’t worked.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var givenString = 'THis is a $ample $tring'
var pattern = /$/g
console.log(givenString.replace(pattern,"S")

the replace function works for any other functions but won’t work for $ sign and How can I replace it with replace function?

>Solution :

You can use replaceAll or escape the special character

1 – replaceAll

givenString.replaceAll('$', '*')

2 – escaping regex

var givenString = 'THis is a $ample $tring'
var pattern = /\$/g
console.log(givenString.replace(pattern,"S")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading