查找子字符串并插入另一个字符串 [英] Finding a substring and inserting another string
本文介绍了查找子字符串并插入另一个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个变量,字符串的长度没有固定,有时像
Suppose I have a variable that the the length of string is not fixed, sometimes like
var a = xxxxxxxxhelloxxxxxxxx;
有时像
var a = xxxxhelloxxxx;
我不能使用 substr()
因为位置不一样。
I can't use substr()
because the position is not identical.
如何在字符串中找到字符串hello并在hello之后插入一个字符串world?
(欢迎使用JavaScript或jQuery方法)
How can I found the string "hello" in the string and insert a string "world" after "hello"? (method in JavaScript or jQuery are welcomed)
谢谢
推荐答案
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>
这篇关于查找子字符串并插入另一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文