0

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

3 Answers 3

1

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'.

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

4 Comments

Why would you escape - outside a character class?
Because if you always escape the -, you never forget to. That's how I was taught =)
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.
this is my code: var reg = new RegExp(lang + "-(.+);"); text = text.replace(reg, ""); debugger return error Unexpected quantifier on first code line
0

Use new RegExp(lang + '-(.+);')

Comments

0

Try this:

var re = new RegExp(lang+"-(.+);");
str1 = str1.replace(re, replacement);

Comments

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.