I want to add space in the string before and after certain characters.
var x = "asdasdasdasd+adasdasdasd/asdasdasdasd*asdasdasd-asdasdasd:asdasdasdadasdasd?";
I want to add space before and after
var separators = ['+', '-', '(', ')', '*', '/', ':', '?'];
So the output will be like
asdasdasdasd + adasdasdasd / asdasdasdasd * asdasdasd - as ( dasd ) asd : asdasdasdadasdasd ?
You can use a Regex for that.
for (var i = 0; i < separators.length; i++) {
var rg = new RegExp("\\" + separators[i], "g");
x = x.replace(rg, " " + separators[i] + " ");
}
You may use something like that:
var str = x.replace(new RegExp('\\' + separators.join('|\\'), 'g'), ' $& ')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With