如何在文本块中查找和替换字符串?

时间:2011-10-31 02:13:03

标签: javascript replace

给出一个字符串块,如:

var copy = "Hello world what is the day @James Bond blah bah blah blah...";

使用jQuery / JS,给出:

var term = "James Bond";
var id = "XXXXXX";

如何找到与'@' + term的所有匹配并返回如下内容:

"Hello world what is the day @[XXXXXX:James Bond] blah bah blah blah..."

由于

2 个答案:

答案 0 :(得分:5)

只需使用替换功能:

var term = "James Bond", id = "XXXXXXX";
"Hello world what is the day @James Bond blah bah blah blah...".replace("@"+term, "@["+id+":"+term+"]");

答案 1 :(得分:1)

var toReplace = "@" + term
var replaceWith = "@[" + id + ":" + term + "]"

从那里你应该能够使用普通的字符串替换功能。