Mirza Delic
Mirza Delic

Reputation: 4349

javascript regex replace variable

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.

Upvotes: 0

Views: 3962

Answers (1)

falsetru
falsetru

Reputation: 369444

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.

Upvotes: 7

Related Questions