JavaScript & jQuery Tutorials

JS Home Right Arrow JS Reference Right Arrow String Right Arrow replace()

replace()  String  instance method

Description

Returns a new string containing some or all of the matches of a replaced pattern.

  • The pattern to replace can be a string or a regular expresion.
  • For each match the pattern can be replaced by another string or the result of a called function.

Syntax


Signature Description
aString.replace(regexp|substr, replacementSubstr|function)Returns a new string containing some or all of the matches of a replaced pattern.

Parameters


Parameter Description
regexpA regular expression or RegExp object or substr.
substrA part of the string to be replaced.
replacementSubstrthe string to replace substr or one of the following patterns:
  • $$ - inserts a '$' symbol.
  • $& - inserts matched substring.
  • $` - inserts portion of the string preceding matched substring.
  • $' - inserts portion of the string following matched substring.
  • $n - if first argument is a RegExp object, inserts the nth parenthesized submatch string.
functionan invoked Function with the following arguments:
  • str - matched substring.
  • p1,pn - if first argument is a RegExp object, inserts the nth parenthesized submatch string.
  • offset - offset of matched substring within total string (s).
  • s - the full string being examined.
  • Other things to note:
    • The number of arguments passed to a function depends on whether the first argument was a RegExp object, and if so, the number of parenthesized submatches specified.

Examples

The code below replaces part of a string.


// Create a string variable.
  var aNewSentence = 'I like to shine my nose';
// Replace part of the string.
alert(aNewSentence.replace('nose', 'shoes'));

Press the button below to action the above code:

Related Tutorials

JavaScript Basic Tutorials - Lesson 8 - Strings



  

go to home page Homepage go to top of page Top