in JavaScript replace () Summary _javascript tips

Source: Internet
Author: User

About definitions

The replace () method replaces some characters in a string with some other characters, or replaces a substring that matches a regular expression.

About grammar

Stringobject.replace (regexp/substr,replacement)

About parameters

Parameters Describe

Regexp/substr

Necessary. The RegExp object that prescribes the substring or pattern to be replaced.

Note that if the value is a string, it is used as the direct text pattern to retrieve, not first converted to the RegExp object.

Replacement Necessary. A string value. Provides a function that replaces text or generates alternate text.


1, the first parameter regexp/substr, the use of regular expressions with the global identifier G, you can replace all the matching substrings, otherwise it will only match once.

For example:

var str = "AAAAA"; 
var str1 = str.replace ("A", "B");
var str2 = str.replace (/a/g, "B");

Run Result: str1-> "Baaaa", str2-> "BBBBB"

2, the second parameter replacement, can be a string or function, can also be the specific meaning of the $ character.

character Replace text
$, $ 、...、 $99 Text that matches the 1th to 99th subexpression in RegExp.
$& The substring that matches the regexp.
$` The text located on the left side of the matching substring.
$' The text that is located to the right of the matching substring.
$$ The direct measure symbol.

A. Examples of function:

var str = "111222AA";
Str.replace (/(\d{3})/g, function (word) {return
 "B";
});

Run Result: "Bbaa"

Examples of B. $

var str = "1234567890";
Str.replace (/(\d{3}) (\d{3}) (\d{4})/g, "$1-$2-$3");

Run Result: "123-456-7890"

Note: Most of the time is to use the combination of regexp and $ to implement the requirements, so it is necessary to know some basic regular expression rules.

String substitution string

' I am loser! '. Replace (' Loser ', ' hero ')

I am hero!
Using strings directly allows you to turn from loser to hero, but if you have 2 loser, you can't turn hero together.

' I am loser,you are loser '. Replace (' Loser ', ' hero ');
I am Hero,you are loser

The regular expression is replaced with a string

' I am loser,you are loser '. Replace (/loser/g, ' hero ')
//i am Hero,you are

Using regular expressions and changing the regular global property to True allows all loser to become hero

Interesting substitution characters

Replacevalue can be a string. If there are several specific characters in the string, they are converted to a specific string.

Character replacement text
$& a string that matches a regular match
$ ' matches the character to the left of the string
$ ' matches the character to the right of the string
$1,$2,$,3,..., $n Matching results in matched results
Use $& characters to add braces to matching characters

var sstr= ' discusses the use of Replace in regular expressions ';
Sstr.replace (/Regular expression/, ' {$&} ');
Discuss the use of Replace in {regular expression}
Replace content with $ ' and $ ' characters

' ABC '. Replace (/b/, "$ '");
Aac
' ABC '. Replace (/b/, "$ '");
Acc
Combining a new string with a grouping match

' nimojs@126.com '. Replace (/(. +) (@) (. *)/, "$2$1")
//@nimojs
The Replacevalue parameter can be a function

The Replacevalue in Stringobject.replace (Searchvalue,replacevalue) can be a function.
If Replacevalue is a function, then the arguments of this function will have n+3 arguments (n is the number of matches to the regular)

See examples to help understand:

function logarguments () { 
 console.log (arguments);
["Nimojs@126.com", "Nimojs", "@", "126.com", 0, "nimojs@126.com"] 
 return ' Returns the value will replace the match to the target '
}
Console.log (
 ' nimojs@126.com '. Replace (/(. +) (@) (. *)/,logarguments)
)

Parameters are

Matching to the string (this example is nimojs@126.com, recommended to modify the code above the regular to see matching characters to help understand)
If you are using a group match for more than one, there is no such argument. (The argument for this example is "Nimojs", "@", "126.com".) Recommended modifications regular for/nimo/view the arguments value returned in the console)
Match the corresponding index position of the string (this example is 0)
Raw string (This example is nimojs@126.com)
Use a custom function to change the a-g string to lowercase

' JAVASCRIPT '. Replace (/[a-g]/g,function () {return
 arguments[0].tolowercase ();
})
Javascript

Use custom functions to make callback substitutions to remove single quotes from inline styles

' <span style= ' font-family:\ ' Microsoft Ya Black '; >demo</span> '. Replace (/\ ' [^ ']+\ '/g,function () {  
 var sresult=arguments[0];
 Console.log (Sresult)//' Microsoft Ya-black '
 sresult=sresult.replace (/\ '/g, ');
 Console.log (sresult);
Microsoft ya
-
black return sresult;} <span style= "font-family: Microsoft James Black;" >demo</span>

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.