2017-06-13 133 views
0

我想从字符串中删除两个标记内的特定系列元素。 我会告诉你一个更清晰的例子。从javascript中删除特定字符到另一个字符串中的元素?

这是我的字符串,从第一个Closure括号中的第一个方块开始,我想要删除里面的元素和脚本。

var x = 'black , [ element ] , blue , green , [ repeated element ]' 

而且结果应该是:

var x = 'black , blue , green , [ repeated element ]' 

我想这个代码,但我无法找到一个特定的删除方式。

var x = 'black , [ element ] , blue , green , [ repeated element ]' 
x = x.substring(0, x.indexOf('[')); 
document.write(x); 

回答

1

试试这个

的第一场比赛只x.replace(/\[[^\]]*\]\s*,?/, "")

所有比赛x.replace(/\[[^\]]*\]\s*,?/g, "")

function myFunction() { 
 
    var str = 'black , [ element ] , blue , green , [ repeated element ]'; 
 
    var res = str.replace(/(,\s*\[[^\]]*\])|(\[[^\]]*\]\s*,?)/, ""); 
 
    document.getElementById("demo").innerHTML = res; 
 
}
<!DOCTYPE html> 
 
<html> 
 
<body> 
 

 
<p>Click the button to replace</p> 
 

 
<p id="demo"></p> 
 

 
<button onclick="myFunction()">Try it</button> 
 

 

 

 
</body> 
 
</html>

1

试试这个

x = x.substring(0,x.indexOf('[')) + x.substring(x.indexOf('] ,') + 3); 
+0

thanx man!是工作! – Paulvan

相关问题