The first time you found the Replace () method in JavaScript is to use the Str.replace ("-", "!") directly. Only the first matching character will be replaced. and Str.replace (/-/g, "!") You can replace all the matching characters (G is the global flag).
--------------------------------------------------------
Using the Replace method
Grammar
Stringobj.replace (Rgexp, ReplaceText)
The syntax for the Replace method includes the following sections:
Partial description
Stringobj required option. The String object or text to perform the substitution. The object is not modified by the Replace method.
Rgexp required option. A regular expression object that describes what to look for.
ReplaceText required option. is a string object or literal, and the position in each matching rgexp in Stringobj is replaced with the text contained in that object.
The following example shows the use of the Replace method:
function ReplaceDemo()
{
var r, re;
var s = "The quick brown fox jumped over the lazy yellow dog.";
re = /fox/i;
r = s.replace(re, "pig");
return(r);
}
另外, replace 方法也可以替换模式中的子表达式。 下面的范例演示了交换字符串中的每一对单词:
function ReplaceDemo()
{
var r, re;
var s = "The quick brown fox jumped over the lazy yellow dog.";
re = /(S+)(s+)(S+)/g;
r = s.replace(re, "$3$2$1"); //交换每一对单词。
return(r);
}
The replace () method in JavaScript if used directly with Str.replace ("-", "!") Only the first matching character will be replaced. Str.replace (/-/g, "!") You can replace all the matching characters (G is the global flag).