Javascript String replaceAll(search, replace)

Description

Javascript String replaceAll(search, replace)


/* http://stackoverflow.com/a/1141816 */
String.prototype.replaceAll = String.prototype.replaceAll||function(search, replace) {
    if (replace === undefined) {
        return this.toString();
    }/* w w w .  jav a2  s  . c  o  m*/
    return this.split(search).join(replace);
}

Javascript String replaceAll(search, replace)

String.prototype.replaceAll = function (search, replace) {
    var string        = this,
        replaceLength = replace.length,
        searchLength  = search.length,
        start         = string.indexOf(search);

    while (start !== -1) {
        string = string.substring(0, start) + replace + string.substring(start + search.length);
        start  = string.indexOf(search, start + replaceLength);
    }/*from  w w  w .j  a  v  a2 s .co  m*/

    return string;
};

Javascript String replaceAll(search, replace)

String.prototype.replaceAll = function(search, replace)
{
    //if replace is not sent, return original string otherwise it will
    //replace search string with 'undefined'.
    if (replace === undefined) {
        return this.toString();
    }// ww w.  j  a  v a  2s .  c  o  m

    return this.replace(new RegExp('[' + search + ']', 'g'), replace);
};

Javascript String replaceAll(search, replace)

String.prototype.replaceAll = function(search, replace) {
    if (replace === undefined) {
        return this.toString();
    }/*from   w  w  w  .  j  a  v  a  2 s.  c  om*/
    return this.split(search).join(replace);
}



PreviousNext

Related