Please, help me. I have a variable lang and i know that after this variable must go characters -(.+);
For example, i would have written it in C # so - regexString = lang + "-(.+);";
But in javascript this code not correct: str1 = str1.replace(lang+"-(.+);", replacement); because there must use /.../, but i don't know how to write correct
Add a comment
|
3 Answers
There is a dynamic way to create regexps in javascript:
new RegExp(lang+'\-(.+)')
(I also escaped the -.)
So to do a replace:
str.replace(new Regexp(lang+'\-(.+)'), replacement)
If you want to replace more than 1:
str.replace(new Regexp(lang+'\-(.+)', 'g'), replacement)
The 'g' flag is for 'global'.
4 Comments
ThiefMaster
Why would you escape
- outside a character class?Rudie
Because if you always escape the
-, you never forget to. That's how I was taught =)Stephen Chung
good point. That's how I like to do it as well -- never want to accidentally forget to escape a dash or another symbol and spend the next few days pulling out hair.
roman
this is my code:
var reg = new RegExp(lang + "-(.+);"); text = text.replace(reg, ""); debugger return error Unexpected quantifier on first code line