简体   繁体   中英

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.

JSFiddle (check js console)

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:

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.

$& corresponds to the matched substring, whereas $1 makes it seem like there are multiple matches in the RegExp object.

Reference here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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