匹配多个值并将重复值替换为一个值

时间:2016-05-19 04:57:14

标签: javascript regex string replace match

我有一个像下面这样的字符串。在字符串中搜索字母。结果是x,x,x,y,y,y。x,y重复三次。我的问题是如何用一个值替换重复的相同值。我需要啊答案比如x,y

function myFunction() {
    var str = "-10x+10x-10x-10y+6y-8y";
    var result = str.match(/[a-z]/g);
    document.getElementById("demo").innerHTML = result;
}
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>

2 个答案:

答案 0 :(得分:2)

使用negative look ahead assertion

function myFunction() {
    var str = "-10x+10x-10x-10y+6y-8y";
    var result = str.match(/([a-z])(?!.*\1)/g);
    document.getElementById("demo").innerHTML = result;
}
<button onclick="myFunction()">Try it</button>

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

Regex explanation here

Regular expression visualization

答案 1 :(得分:1)

要获取唯一变量名称,可以在正则表达式后添加此行

var map = {}; 
result.forEach( function(val){ map[val] = true } );
result = Object.keys(map)

<强>样本

&#13;
&#13;
    var str = "-10x+10x-10x-10y+6y-8y";
    var result = str.match(/[a-z]/g);
    var map = {}; 
    result.forEach( function(val){ map[val] = true } );
    result = Object.keys(map);
    document.body.innerHTML += JSON.stringify(result, 0, 4)
&#13;
&#13;
&#13;