Replace method in JavaScript Posted on 2004-12-16 16:20 min reading (622)
Comments (2)
edit
Favorites href = "http://www.cnblogs.com/mindotnet/services/pingback.aspx" Rel = "pingback" />
The first discovery of the Replace () method in JavaScript only replaces the first matching character if you use str.replace ("-", "!").
Replace () The replace () Method Returns the string That Results when You Replace Text Matching Its First Argument (a Regular Expression)
WITH
The text of the second argument (a string). IF The g (global) Flag is not set
in
The Regular Expression Declaration,
THIS
Method replaces Only the first obscurrence of the pattern. for example,
VAR
s
=
"
Hello. Regexps are fun.
"
; S
=
S.Replace
/
/.
/
,
"
!
"
);
//
Replace First Period with an Exclamation Pointalert (s);
PROduces the string "Hello
!
Regexps Are Fun. "INCLUDING THE G FLAG WILL CAUSE The Interpreter TO Perform A Global Replace, Finding and Replacing Every Matching Substring. For Example,
VAR
s
=
"
Hello. Regexps are fun.
"
; S
=
S.Replace
/
/.
/
g,
"
!
"
);
//
Replace All Periods with Exclamation Pointsalert (s);
Yields
THIS
Result: "Hello
!
Regexps Are Fun
!
"