A detailed explanation of the Replace method in JavaScript _javascript tips

Source: Internet
Author: User

Definitions and usage

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

Stringobject.replace (regexp/substr,replacement)

Parameters Description
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.
return value

A new string that is replaced with replacement for the first match of RegExp or after all matches have been made.

Regular characters

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

Character Replace text
$$ Direct measure sign (just as ' $$ ' character used)
$& A string that matches a regular match
$` Matches the character to the left of the string
$' Match the character to the right of the string
$1,$2,$,3,..., $n Corresponding packet matching results in matching results

The following examples for you to introduce:

Example 1

In this case, we'll use "w3school" to replace "Microsoft" in the string:

<script type= "Text/javascript" >
var str= "Visit microsoft!"
document.write (Str.replace (/microsoft/, "W3school")
</script>

Output:

Visit w3school!

Example 2

In this case, we will perform a global substitution, which is replaced with "W3school" whenever "Microsoft" is found:

<script type= "Text/javascript" >
var str= "Welcome to microsoft! "
Str=str +" We are proud to announce this is Microsoft has "
Str=str +" one of the largest WEB developers sites in t He world. "
document.write (Str.replace (/microsoft/g, "W3school")
</script>

Output:

Welcome to w3school! We are proud to announce that W3school
has one of the largest WEB developers sites in the world.

Example 3

You can use the code provided in this example to ensure that matching string uppercase characters are correct:

Text = "JavaScript Tutorial";
Text.replace (/javascript/i, "JavaScript");

Example 4

In this case, we'll convert "Doe, John," to "John Doe" in the form of:

Name = "Doe, John";
Name.replace (/(\w+) \s*, \s* (\w+)/, "$ $");

Example 5

In this case, we'll replace all the curly quotes with straight quotes:

Name = ' "A", "B";
Name.replace ([^ "]*)"/g, "' $ '");

Example 6

In this case, we will convert the first letter of all words in the string to uppercase:

Name = ' AAA bbb CCC ';
Uw=name.replace (/\b\w+\b/g, function (word) {return
 word.substring (0,1). toUpperCase () +word.substring (1);}
 );

Regular replacement 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

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}
replaces the content ' ABC ' with $ ' and $ ' characters
. Replace (/b/, "$");
AAC
' abc '. Replace (/b/, "$ '");
ACC
uses group matching to combine the new string
' 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>

The above content is small to introduce the avascript in the Replace method, I hope you like.

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.