JavaScript Replace function

Source: Internet
Author: User
Tags regular expression

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).

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.