我们说我有一个字符串:
"but i [C#min] do [G#min] believe there's"
如何将该字符串转换为:
"but i do believe there's" (basically removing everything in-between '[' and ']')
我希望[C#min]
& [G#min]
存储在另一个数组中。
答案 0 :(得分:2)
var a = "but i [C#min] do [G#min] believe there's";
console.log(a.replace(/\[(.[^\[\]]*)\]/g, '')); // "but i do believe there's"
console.log(a.match(/\[(.[^\[\]]*)\]/g)); // ["[C#min]", "[G#min]"]

RegExp与[
,]
之间的所有内容相匹配,但[
,]
除外。
您可能需要删除替换周围留下的额外空白区域。
答案 1 :(得分:1)
您可以使用正则表达式:
var text = "but i [C#min] do [G#min] believe there's";
var regexp = /(\[[^\]]*\])/g;
var matches = text.match(regexp);
text = text.replace(regexp, '').replace(/ /g, ' ');
console.log(text);

matches
将包含数组["[C#min]", "[G#min]"]
。
注意:文本的第二个replace
处理错误保留的双重空格。
答案 2 :(得分:0)
尝试这种直截了当的方式:
var str = "but i [C#min] do [G#min] believe there's";
var start, stop, newStr = '', removed = '', counter =1;
while(str.search(/\[.*\]/g) > 0) {
start = str.indexOf('[');
stop = str.indexOf(']');
newStr += str.substring(0, start);
removed += str.substring(start, stop+1);
str = str.substring(stop+1, str.length);
counter++;
if(counter > 3) break;
}
newStr += str;
console.log(newStr);
答案 3 :(得分:0)
没有正则表达式,简单方法:
var string = "but i [C#min] do [G#min] believe there's";
array = [];
filteredString = ""
for (i=0;i<string.length;i++){
if (string[i] != '[') {
filteredString += string[i];
continue;
}
newstring = ""+string[i];
do {
newstring += string[++i];
} while (string[i]!=']');
array.push(newstring);
}
console.log(array);
console.log(filteredString);
&#13;
答案 4 :(得分:0)
您可以使用正则表达式查找括号中的字符串,然后使用String.replace()
将其删除。剥离的部分将在一个数组中,用于您需要的任何用途。
var input = "but i [C#min] do [G#min] believe there's";
var reg = /\[(.*?)\]/g; // Patthen to find
var matches = input.match(reg); // Find matches and populate array with them
var output = input.replace(reg, "").replace(/\s\s/g, " "); // Strip out the matches and fix spacing
console.log(matches); // Just for testing
console.log(output); // Result
答案 5 :(得分:0)
您可以按[:
分割字符串function parseString(input) {
output = {
values: [],
result: ""
};
input = input.split('[');
for (var index = 0; index < input.length; index++) {
var closingPosition = input[index].indexOf("]");
if ((index > 0) && (closingPosition + 1)) {
output.values.push('[' + input[index].substring(0, closingPosition) + ']');
if (input[index].length > closingPosition) {
output.result += input[index].substring(closingPosition + 1);
}
} else {
output.result += input[index];
}
}
return output;
}