Sponsored Ad

Friday, March 26, 2010

How to replace a string in a given string with new string using JavaScript

This JavaScript utility helps you to replace a particular test in a given string with a new text values.

just pass these parameters in given function , for example:

replace(‘Original string’, ‘string’ ,’new string’);

in above call We are replacing ‘string’ values in ‘Original string’ with ‘new string’

 

function replace(string,text,newtext) {
// Replaces text with newtext in string
    var strLength = string.length, txtLength = text.length;
    if ((strLength == 0) || (txtLength == 0)) return string;

    var i = string.indexOf(text);
    if ((!i) && (text != string.substring(0,txtLength))) return string;
    if (i == -1) return string;

    var newstr = string.substring(0,i) +newtext;

    if (i+txtLength < strLength)
        newstr += replace(string.substring(i+txtLength,strLength),text,newtext);

    return newstr;
}

0 comments:

Post a Comment

Sponsored Ad

Website Update

Followers