我有字符串
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从字符串中删除所有加号,将加号留在括号内
我有字符串
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从字符串中删除所有加号,将加号留在括号内
我会沿着这些思路去做:
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();
另一种解决方法(不知道是否性能更好)将使用以下内容:
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:第二种解决方案
使用以下代码,让我知道它是否有效:)
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,' '));
}