繁体   English   中英

jQuery-查找并替换子字符串

[英]jQuery - find and replace substring

假设我有这样的字符串

'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) );

但是替换失败了...那么近,到目前为止。

您可以很容易地使用regex ...这将适用于所有字符串。

JSFiddle (检查js控制台)

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/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/replace

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM