Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery: how to replace all between certain characters?

Tags:

jquery

replace

I have searched for a general solution to this but only find answers to peoples specific questions.

Basically, I want to know how to generally use .replace() to replace items in between any kind of characters in a string, eg:

Replace all text in between and inclusive of abc and xyz eg: abc text to be replaced xyz

or replace all text in between and inclusive of <img and /> eg: <img src="image.jpg" />

Can anyone help me out or point me in the direction of a good tute on this?

Thanks! Let me know if I need to clarify more.

like image 526
MeltingDog Avatar asked Jun 19 '26 22:06

MeltingDog


1 Answers

What you are looking for are called regular expressions. For more information, you can visit a site like: http://www.regular-expressions.info/

Note that regular expressions are not specific to JavaScript.

For your specific example:

string.replace(/abc.+xyz/,"abc"+newString+"xyz");

. means any character, and + means one or more occurences.

If you have more than one replacement to do, try:

string.replace(/abc.+?xyz/g,"abc"+newString+"xyz");

g stands for general, and ? is the lazy quantifier, meaning that it will stop at the next occurence of xyz in the string.

like image 130
Christophe Avatar answered Jun 21 '26 10:06

Christophe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!