Add space in the string before and after certain characters

别来无恙 提交于 2019-12-11 04:08:49

问题


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 ?

回答1:


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] + " "); 
}



回答2:


You may use something like that:

var str = x.replace(new RegExp('\\' + separators.join('|\\'), 'g'), ' $& ')



回答3:


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);
}



回答4:


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.



来源:https://stackoverflow.com/questions/19313874/add-space-in-the-string-before-and-after-certain-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!