1

I'm trying to replace more than 1 word in same string, with RegExp, but it seems is not working, i tryied some answers here in stackoverflow, but with no result

var _tpl = "time working $times, not now $times"
var reg = "$times"
var regexp = new RegExp(reg, "g")
var replaceFor = 1
var _newTpl = _tpl.replace(regexp, replaceFor)
console.log(_newTpl)

some advice?

CRice
32.6k5 gold badges63 silver badges75 bronze badges
asked Apr 16, 2018 at 22:29

2 Answers 2

2

$ is a special character in a regular expression: you must escape it.

var _tpl = "time working $times, not now $times"
var reg = "\\$times"
var regexp = new RegExp(reg, "g")
var replaceFor = 1
var _newTpl = _tpl.replace(regexp, replaceFor)
console.log(_newTpl)

Note that you need two \s in order to put a single literal \ in the resulting string. If you create the regular expression directly, with regex syntax and not string syntax, only use one \:

const regexp = /\$times/g;
answered Apr 16, 2018 at 22:33
Sign up to request clarification or add additional context in comments.

Comments

2

You have to escape regex' special characters before passing them to new RegExp.

var reg = "\\$times"

var _tpl = "time working $times, not now $times"
var reg = "\\$times"
var regexp = new RegExp(reg,"g")
var replaceFor = 1
var _newTpl = _tpl.replace(regexp, replaceFor)
console.log(_newTpl)

answered Apr 16, 2018 at 22:32

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.