在 javascript 中将字符串中的元素从特定字符删除到另一个字符?

Delete elements inside a string from a specific character to another in javascript?

我想从字符串中删除两个标记内的一系列特定元素。

我举个例子让你更清楚。

这是我的字符串,我想从第一个闭括号的第一个左方括号中删除里面的元素和括号。

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

试试这个

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

试试这个

仅限第一场比赛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>