【问题标题】:Match the multiple values and replace the repeated values with one value匹配多个值并将重复值替换为一个值
【发布时间】:2016-05-19 04:57:14
【问题描述】:

我有一个字符串,如下所示。匹配字符串中的字母。结果是x,x,x,y,y,y。x,y 重复三次。我的问题是如何用一个值替换重复的相同值。我需要像 @ 这样的答案987654322@.

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>

【问题讨论】:

    标签: javascript regex string replace match


    【解决方案1】:

    使用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

    【讨论】:

    • 谢谢@pranav c balan。你能解释一下正则表达式吗?
    • @PranavCBalan 如果 x 和 y 不总是在一起,这会给出相同的预期结果吗?
    • @PranavCBalan 很棒,测试也一样 +1
    【解决方案2】:

    要获得唯一的变量名称,您可以在正则表达式之后添加这一行

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

    演示

        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)

    【讨论】:

      猜你喜欢
      • 2016-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-21
      • 1970-01-01
      • 2021-11-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多