gpt4 book ai didi

javascript - 正则表达式替换和追加字符串

转载 作者:行者123 更新时间:2023-11-30 20:58:38 24 4
gpt4 key购买 nike

我设法删除了字符串中的每个“-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>

最佳答案

对于情况 2,您可以将 vi-([-\w]+)-xx 替换为 vi-$1
vi-([-\w]+) 到案例 3 的 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>

关于javascript - 正则表达式替换和追加字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47361395/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com