search
HomeWeb Front-endJS TutorialJS replace method_javascript skills

定义和用法
replace() 方法用于在字符串中用一些字符替换另一些字符,或替换一个与正则表达式匹配的子串。

语法
stringObject.replace(regexp/substr,replacement)

参数 描述
regexp/substr

必需。规定子字符串或要替换的模式的 RegExp 对象。

请注意,如果该值是一个字符串,则将它作为要检索的直接量文本模式,而不是首先被转换为 RegExp 对象。

replacement 必需。一个字符串值。规定了替换文本或生成替换文本的函数。

返回值

一个新的字符串,是用 replacement 替换了 regexp 的第一次匹配或所有匹配之后得到的。

说明

字符串 stringObject 的 replace() 方法执行的是查找并替换的操作。它将在 stringObject 中查找与 regexp 相匹配的子字符串,然后用 replacement 来替换这些子串。如果 regexp 具有全局标志 g,那么 replace() 方法将替换所有匹配的子串。否则,它只替换第一个匹配子串。

replacement 可以是字符串,也可以是函数。如果它是字符串,那么每个匹配都将由字符串替换。但是 replacement 中的 $ 字符具有特定的含义。如下表所示,它说明从模式匹配得到的字符串将用于替换。

字符 替换文本
$1、$2、...、$99 与 regexp 中的第 1 到第 99 个子表达式相匹配的文本。
$& 与 regexp 相匹配的子串。
$` 位于匹配子串左侧的文本。
$' 位于匹配子串右侧的文本。
$$ 直接量符号。

Note: ECMAScript v3 stipulates that the parameter replacement of the replace() method can be a function instead of a string. In this case, the function is called for each match and the string it returns is used as the replacement text. The first parameter of this function is a string matching the pattern. The next argument is a string that matches the subexpression in the pattern, and there can be 0 or more such arguments. The next parameter is an integer that declares the position in the stringObject where the match occurs. The last parameter is the stringObject itself.

More basic examples can be viewed here: http://www.jb51.net/w3school/js/jsref_replace.htm

The parameter replacement of the replacement() method can be function instead of string. In this case, the function is called for each match and the string it returns is used as the replacement text. The first parameter of this function is a string matching the pattern. The next argument is a string that matches the subexpression in the pattern. There can be 0 or more such arguments. The next parameter is an integer that declares the position in the stringObject where the match occurs. The last parameter is the stringObject itself.

The following shows several ways to repalce javascript regular expressions. Some ways we rarely see elsewhere, such as the second and third-party methods.

Copy code The code is as follows:

//The following example is used to get the two urls parameters and return the real Url before urlRewrite
var reg=new RegExp("(http://www.qidian.com/BookReader/)(\d ),(\d ).aspx","gmi") ;
var url="http://www.qidian.com/BookReader/1017141,20361055.aspx";

//Method 1, the simplest and most commonly used method
var rep=url.replace(reg,"$1ShowBook.aspx?bookId=$2&chapterId=$3");
alert(rep);

//Method 2, using a callback function with fixed parameters
var rep2=url.replace(reg,function(m,p1,p2,p3){return p1 "ShowBook.aspx?bookId=" p3 "&chapterId =" p3});
alert(rep2);

//Method 3, using a callback function with non-fixed parameters
var rep3=url.replace(reg,function(){var args=arguments; return args[1] "ShowBook.aspx?bookId=" args [2] "&chapterId=" args[3];});
alert(rep3);


//Method 4
//Method 4 is very similar to method 3. In addition to returning the replaced string, you can also obtain the parameters separately

[code]
var bookId;
var chapterId;
function capText()
{
var args=arguments;
bookId=args[2];
chapterId=args[3];
return args[1] "ShowBook.aspx?bookId=" args[2] "&chapterId=" args[3];
}

var rep4=url.replace(reg,capText);
alert(rep4);
alert(bookId);
alert(chapterId);


//In addition to using the replace method to obtain the grouping of regular expressions, you can also use the test and exec methods to obtain the grouping, but the methods are different
var reg2=new RegExp("(http:/ /www.qidian.com/BookReader/)(\d ),(\d ).aspx","gmi");
var m=reg2.exec("http://www.qidian.com/BookReader /1017141,20361055.aspx");
var s="";
//Get all groups
for (i = 0; i s = s m[i] "n"; 
 }
alert(s);

bookId=m[2];
chapterId=m[3];
alert(bookId);
alert(chapterId);


//Use the test method to get the group
var reg3=new RegExp("(http://www.qidian.com/BookReader/)(\d ),(\d ).aspx", "gmi");
reg3.test("http://www.qidian.com/BookReader/1017141,20361055.aspx");
//Get three groups
alert(RegExp.$1 );
alert(RegExp.$2);
alert(RegExp.$3);

var str="www.baidu.com";
//str.format("good","q")
str.replace(new RegExp("(\.)(bai)du "," g "), function () {
for (var I = 0; I & lt; arguments.length; i)
{
Document.write (arguments [i]" & lt; br/& gt ;");
                                                                                                                                                                            . ---------------
");
      });

Two examples (to prove that the results of replacing regular parameters and character parameters are different):

alert("123".replace("1",function(){var un;return un;})); //pop up undefined23
alert("123".replace(new RegExp("1" ),function(){var un;return un;})); //Pop up 23

Some examples:


replace() is the simplest The only capability is simple character replacement. For example:


[Ctrl A Select all Note: If you need to introduce external Js, you need to refresh to execute
]


I want everyone You can see the result after running it, it only replaced the first letter. But if you add a regular expression, the result will be different! replace() supports regular expressions, it can match characters or strings according to the rules of regular expressions, and then replace them!

[Ctrl A Select all Note:
If you need to introduce external Js, you need to refresh to execute
]


But the result is still the same There are no changes, and if you are familiar with regex, this will not be a problem for you. It's OK with a little modification.
Copy code
The code is as follows:






You can also do this and see the effect!
Copy code
The code is as follows:






The examples I give here are very simple applications. At this point, replace() is directly proportional to your ability to use regular expressions. The stronger your regular expression is, haha, the crazier you will fall in love with it.
Of course, the reason why I recommend replace() here is not because it can cooperate with regular expressions, but because it can also cooperate with functions and exert powerful functions.
Let’s look at a simple example first: capitalize the first letters of all words.
Copy code
The code is as follows:






It can be seen from the above that when the regular expression When the "g" flag is present, it means that the entire string will be processed, that is, the transformation of the change function will be applied to all matching objects. This function has three or more parameters, and the specific number depends on the regular expression.
With the cooperation of functions and regular expressions, the function of replace() to process strings has become unprecedentedly powerful!
Finally, let me give you an example. It is so simple to use replace() to reverse all the words in a string.
Copy code
The code is as follows:


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.