gpt4 book ai didi

javascript - 查找子字符串并插入另一个字符串

转载 作者:数据小太阳 更新时间:2023-10-29 04:53:37 25 4
gpt4 key购买 nike

假设我有字符串变量,例如:

var a = "xxxxxxxxhelloxxxxxxxx";

或:

var a = "xxxxhelloxxxx";

我想在 "hello" 之后插入 "world"

我不能使用 substr() 因为无法提前知道位置。我如何在 JavaScript 或 jQuery 中执行此操作?

最佳答案

var a = "xxxxhelloxxxxhelloxxxx";
a = a.replace(/hello/g,"hello world"); // if you want all the "hello"'s in the string to be replaced
document.getElementById("regex").textContent = a;

a = "xxxxhelloxxxxhelloxxxx";
a = a.replace("hello","hello world"); // if you want only the first occurrence of "hello" to be replaced
document.getElementById("string").textContent = a;
<p>With regex: <strong id="regex"></strong></p>
<p>With string: <strong id="string"></strong></p>

关于javascript - 查找子字符串并插入另一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5865257/

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