0

How can i replace character with regex, but from variable. Example:

var separator = '-';
text = text.replace(/[-\s]+/g, separator);

this will replace - trailing character with separator, which i the same in this case.

So, i need to set this - character from variable separator:

var separator = '-';
var regex = '/['+separator+'\s]+/g';
text = text.replace(regex, separator);

How can i do this? Thanks.

0

1 Answer 1

7

Use RegExp to dynamically generate regular expression:

function escapeRegExp(string){
    return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}
var regex = new RegExp('[' + escapeRegExp(separator) + '\\s]', 'g');

escapeRegExp comes from Regular Expressions - JavaScript | MDN.

NOTE: You have to escape \, and separator.

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

1 Comment

Also, you might have to escape separator itself, e.g. consider separator = "]"...

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.