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.
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")