JavaScript
Article
By Sam Deering

jQuery Replace All in String

By Sam Deering
Last chance to win! You'll get a... FREE 6-Month Subscription to SitePoint Premium Plus you'll go in the draw to WIN a new Macbook SitePoint 2017 Survey Yes, let's Do this It only takes 5 min

Simple jQuery code snippet to replace all occurrences of characters (or strings) within a string. It could be used to find and replace all substrings found inside a string. Don’t forget to leave out the quotes on the first parameter (the g stands for global, you can also use i for an case insensitive search).

//global search in string
str = str.replace(/find/g,”replace”);
//OR global and case insensitive search in string
str = str.replace(/find/gi,”replace”);

global replace with dynamic var

//global replace
var regex = new RegExp('{'+fieldname+'}', "igm");
$itemForm = $itemForm.replace(regex, fieldvalue);

Also see: jQuery Read Text File Via AJAX.

Demo

--ADVERTISEMENT--

Login or Create Account to Comment
Login Create Account
Recommended
Sponsors
Get the most important and interesting stories in tech. Straight to your inbox, daily.Is it good?