Reputation: 10466
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 ?
Upvotes: 3
Views: 10765
Reputation: 4775
you ca try this | Demo
function fix(val)
{
var separators = ['+', '-', '(', ')', '*', '/', ':', '?'];
var result="";
flag=true;
for(var i=0;i<val.length;i++)
{
flag=true;
for(var j=0;j<separators.length;j++)
{
if(val[i]==separators[j])
{
result += " " + val[i] + " ";
flag=false;
}
}
if(flag)
{
result +=val[i];
}
}
alert(result);
}
Upvotes: 1
Reputation: 639
Well this looks fairly easy...
var separators = ['+', '-', '(', ')', '*', '/', ':', '?'];
var x = "asdasdasdasd+adasdasdasd/asdasdasdasd*asdasdasd-asdasdasd:asdasdasdadasdasd?";
$(separators).each(function (index, element) {
x = x.replace(element, " " + element + " ");
});
Here's a fiddle: http://jsfiddle.net/gPza4/
For the people who want to understand this code, what I basically do is to make the separators array to a jQuery object and then iterate over it while replacing the occurances of those separators in the string x with their "spaced" form.
Upvotes: 0
Reputation: 3578
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] + " ");
}
Upvotes: 3
Reputation: 145368
You may use something like that:
var str = x.replace(new RegExp('\\' + separators.join('|\\'), 'g'), ' $& ')
Upvotes: 3