jQuery - 查找并替换子字符串

jQuery - find and replace substring

本文关键字:字符串 替换 查找 jQuery      更新时间:2023-09-26

假设我有这样的字符串

'Hello, I am ***Groot*** today.'
'This is ***not*** my final form.'
'Test test ***123***'
我想在第一个星号

之前和第二个星号之后添加一些新东西,使其看起来像

'Hello, I am FIRST***Groot***LAST today.'
'This is FIRST***not***LAST my final form.'
'Test test FIRST***123***LAST'

到目前为止,我设法得到了这个

var first =  jQuery(this).html().indexOf("***");
var last  =  jQuery(this).html().lastIndexOf("***");
console.log( jQuery(this).html().substring(first, last+3) );

但我在更换时失败了...那么近,却又那么远。

你可以很容易地使用正则表达式...这将适用于所有字符串。

JSFiddle (check js console)

var str = jQuery(this).text();
str = str.replace(/('*{3}.*'*{3})/, "FIRST$1LAST");
console.log(str);

此外,您实际上不需要创建jQuery对象只是为了获取文本,可以这样做:

var str = this.innerText;
str = str.replace(/'*{3}.*'*{3}/, "FIRST$&LAST");
console.log(str);

我相信替换参数中正确的特殊替换字符应该$&,而不是仅仅为了可读性和最佳实践而$1

$&对应于匹配的子字符串,而$1使 RegExp 对象中有多个匹配项。

参考此处: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace