简体   繁体   English

jQuery-查找并替换子字符串

[英]jQuery - find and replace substring

Let's say I got strings like this 假设我有这样的字符串

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

and I want to add some new stuff before the first and after the second asterix to make it look like 我想在第一个和第二个星号之前添加一些新内容,使其看起来像

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

So far I managed to get this 到目前为止,我设法做到了

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

but I fail on the replacement...so close, yet so far.... 但是替换失败了...那么近,到目前为止。

You can use regex pretty easily... this will work for all of your strings. 您可以很容易地使用regex ...这将适用于所有字符串。

JSFiddle (check js console) JSFiddle (检查js控制台)

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

Also, you don't really need to create the jQuery objects just to get the text, could just do this: 另外,您实际上并不需要创建jQuery对象来获取文本,只需执行以下操作:

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

I believe the correct special replacement character in your replacement parameter should be $& rather than $1 just for readability sake and best practices. 我相信您的替换参数中正确的特殊替换字符应该是$&而不是$1只是出于可读性和最佳实践的考虑。

$& corresponds to the matched substring, whereas $1 makes it seem like there are multiple matches in the RegExp object. $&对应于匹配的子字符串,而$1使得RegExp对象中似乎有多个匹配项。

Reference here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace 此处参考: 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