删除括号外的所有字符串点

时间:2013-06-06 13:28:25

标签: javascript

我有字符串

var string =  .row-4 .col-2.grid-unit+.grid-unit+.grid-unit,.row-4 .col-3 .grid-unit .row-4 .grid-unit:nth-of-type(2n+3) .show-grid+.show-grid-reportdiv

我需要删除所有加号,使用javascript

在字符串的括号内留下加号

2 个答案:

答案 0 :(得分:1)

我会按照这些方式做点什么:

var i, splits, string = ".row-4 .col-2.grid-unit+.grid-unit+.grid-unit,.row-4 .col-3 .grid-unit .row-4 .grid-unit:nth-of-type(2n+3) .show-grid+.show-grid-reportdiv";
splits = string.split(/(\([^)]+\))/);
for (i = 0; i< splits.length; i++) {
    if (splits[i].charAt(0) !== "(") {
        splits[i] = splits[i].replace("+"," ");
    }
}
string = splits.join();

另一种方法(dunno,如果它的性能更好)将使用以下内容:

var string = ".row-4 .col-2.grid-unit+.grid-unit+.grid-unit,.row-4 .col-3 .grid-unit .row-4 .grid-unit:nth-of-type(2n+3) .show-grid+.show-grid-reportdiv";
function replacer (match, offset, string) { 
    var posOpen = string.indexOf("(",offset);
    var posClose = string.indexOf(")",offset);
    // we replace it if there are no more closing parenthesis or if there is one that is located after an opening one.
    if (posClose === -1 || (posClose > posOpen && posOpen !== -1)) {
        return " ";
    } else {
        return "+";
    }
};
string.replace(/\+/g, replacer);

编辑:添加了bergi建议,以便更快地检查循环内部。

EDIT2:第二个解决方案

答案 1 :(得分:0)

使用以下代码,让我知道它是否有效:)

var myString =  ".row-4 .col-2.grid-unit+.grid-unit+.grid-unit,.row-4:nth-of-type(2n+3) .col-3 .grid-unit .row-4 .grid-unit:nth-of-type(2n+3) .show-grid+.show-grid-reportdiv";

var myArray = myString.split(/\(.[\(\)A-Za-z0-9-.+]*\)/);

for(var i = 0; i < myArray.length; i++) { 
  myString = myString.replace(myArray[i], myArray[i].replace(/[+]/g,' ')); 
}