替换引号之间的文本

时间:2014-03-19 11:27:58

标签: jquery regex

我有以下字符串说:

var str = "This is 'first text' and now this is 'second', and many more contents goes here.";

现在,我希望将前两个引号first textsome text之间的文字替换为其他两个引号,并使用secondsome more text等文本替换

最后一个字符串应该是这样的:

This is 'some text' and now this is 'some more text', and many more contents goes here.

实际上我必须在两个文本框的文本更改事件中进行这两个替换。到目前为止,我只能用特定的文字替换,而不是以上条件。

1 个答案:

答案 0 :(得分:1)

如果您想根据文字匹配替换内容,请尝试

var str = "This is 'fisrt text' and now this is 'second', and many more contents goes here.";

var map = {
    "'fisrt text'": "'some text'",
    "'second'": "'more text'"
}

var str2 = str.replace(/'.*?'/g, function (str) {
    return map[str] || ''
});
console.log(str2)

演示:Fiddle


如果您想用位置(索引)替换它

var str = "This is 'fisrt text' and now this is 'second', and many more contents goes here.";

var array = ["'some text'",
    "'more text'"],
    i = 0;

var str2 = str.replace(/'.*?'/g, function (str) {
    return array[i++] || ''
});
console.log(str2)

演示:Fiddle