正则表达式替换并附加字符串

时间:2017-11-18 01:00:20

标签: javascript regex replace append

我成功删除了所有' -xx'在一个字符串中(例1)。 我希望你的帮助让例2和3工作。



function myFunction() {
    var str1 = 'foot zi-cnn-xx vi-sky-xx test vi-axn-xx red';
    var str2 = 'foot zi-cnn vi-sky test vi-axn red';
    
    // Example 1
    // remove every '-xx'
    var res1 = str1.replace(/-xx/g, '');
    document.getElementById("demo1").innerHTML = res1;
    
    // Example 2
    // delete every '-xx' from str1 substring that starts with 'vi'
    // expected: 'foot zi-cnn-xx vi-sky test vi-axn red';
    
    // Example 3
    // add '-xx' to str2, to every substring that starts with 'vi'
    // expected: 'foot zi-cnn vi-sky-xx test vi-axn-xx red';

}

<button onclick="myFunction()">Test this</button>

<p id="demo1"></p>
<p id="demo2"></p>
<p id="demo3"></p>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

对于案例2,您可以将vi-([-\w]+)-xx替换为vi-$1 案例3的vi-([-\w]+)vi-$1-xx

段:

function myFunction() {
    var str1 = 'foot zi-cnn-xx vi-sky-xx test vi-axn-xx red';
    var str2 = 'foot zi-cnn vi-sky test vi-axn red';
    
    // Example 1
    // remove every '-xx'
    var res1 = str1.replace(/-xx/g, '');
    document.getElementById("demo1").innerHTML = res1;
    
    // Example 2
    // delete every '-xx' from str1 substring that starts with 'vi'
    // expected: 'foot zi-cnn-xx vi-sky test vi-axn red';
    var res2 = str1.replace(/vi-([-\w]+)-xx/g, "vi-$1");
    document.getElementById("demo2").innerHTML = res2;
    
    // Example 3
    // add '-xx' to str2, to every substring that starts with 'vi'
    // expected: 'foot zi-cnn vi-sky-xx test vi-axn-xx red';
    var res3 = str2.replace(/vi-([-\w]+)/g, "vi-$1-xx");
    document.getElementById("demo3").innerHTML = res3;

}
<button onclick="myFunction()">Test this</button>

<p id="demo1"></p>
<p id="demo2"></p>
<p id="demo3"></p>