This article briefly introduces the usage of the Javascript replace function. To facilitate your understanding, I believe this article will surely help you gain some benefits.
Javascript replace Function
If you use str. replace ("-","! ") Will only replace the first matched character. str. replace (/-/g ,"! ).
Replace Method
Syntax
StringObj. replace (rgExp, replaceText)
The syntax of the replace method includes the following parts:
Partial description
StringObj is required. String object or text to be replaced. This object will not be modified by the replace method.
RgExp is required. A regular expression object that describes the content to be searched.
ReplaceText is required. Is a String object or text. For each position in stringObj that matches rgExp, it is replaced by the text contained in this object.
The following example demonstrates how to use the replace method in Javascript:
- functionReplaceDemo()
- {
- varr,re;
- vars="Thequickbrownfoxjumpedoverthelazyyellowdog.";
- re=/fox/i;
- r=s.replace(re,"pig");
- return(r);
- }
In addition, the replace method can replace the subexpression in the mode. The following example demonstrates each pair of words in the exchange string:
- FunctionReplaceDemo ()
- {
- Varr, re;
- Vars = "Thequickbrownfoxjumpedoverthelazyyellowdog .";
- Re =/(S +) (s +) (S +)/g;
- R = s. replace (re, "$3 $2 $1"); // exchange each pair of words.
- Return (r );
- }
If the replace () method in JavaScript uses str. replace ("-","! ") Only the first matched character. str. replace (/-/g ,"! ).