Last week I was struggling with string replace function.The requirement was strange but its not in scope of this post. After spending one whole day and achieving the requirement, I have decided to club all the possible usage of replace funcation.
lets start with the simplest form of Replace function.
var str = "The world is beautiful, just you need beautiful heart";
str = str.replace('beautiful', 'lovely');
str = str.replace('beautiful', 'lovely');
In above replace call, the first only occurrence of beautiful will be replaced by heart. The resultant string will be "The world is lovely, just you beautiful heart."
The Replace() function has two arguments
- string or regex to be replaced
- string or function[that return string] to be in placed.
we'll look in every possible scenarios.
Now if I want to make my replace function case insensitive, I do have to make little bit modification.
as follows
var str = "The world is Beautiful, just you need Beautiful heart";
str = str.replace(/beautiful/i, 'lovely');
In above case the the first occurrence of Beautiful will be replaced by lovely.
Now I want to replace all the occurrence of the Beautiful irrespective of case. then a small modification is needed as follows.
var str = "The world is Beautiful, just you need beautiful heart";
str = str.replace(/beautiful/gi, 'lovely');
here all the occurrence of Beautiful/beautiful will be replaced by lovely word.
Now I want to give to be replaced string dynamically it can be achieved as follows.
var str = "The world is Beautiful, just you need beautiful heart"; str = str.replace(/beautiful/gi, strTo()); As we can see here the second parameter of replace function is a call to function which will return some formatted string.
Now in case where the string which is to be replaced is dynamically supplied then we haveto take another approach as followsvar strTarget='beautiful' var str = "The world is Beautiful, just you need beautiful heart"; str = str.replace(strTarget, strTo(),'gi');however this function will only work with firefox, to make it work in IE demands some work around as follows.var strTarget = new RegExp('beautiful', 'gi'); var str = "The world is Beautiful, just you need beautiful heart"; str = str.replace(strTarget, strTo());here we have to create our own regexp that will be supplied to replace function as first parameter, and it works great with IE too...
Comments
Post a Comment