search
HomeWeb Front-endJS TutorialHow to replace string in js?

How to replace string in js?

Jul 28, 2020 am 11:45 AM
javascriptstring

在js中,可以使用str.replace()方法来替换字符串。replace()方法用于在字符串中用一些字符替换另一些字符,或替换一个与正则表达式匹配的子串;然后返回一个新的字符串。

How to replace string in js?

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

语法:

stringObject.replace(regexp/substr,replacement)

How to replace string in js?

返回值

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

说明

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

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

How to replace string in js?

示例:使用 "hello" 替换字符串中的 "hi":

<script type="text/javascript">

var str="hi!";
console.log(str.replace(/hi/, "hello"));

</script>

输出:

hello!

扩展知识replace的用法

1、replace基本用法

<script type="text/JavaScript">
    /*要求将字符串中所有的a全部用A代替*/
    var str = "JavaScript is great script language!";
    //只会将第一个匹配到的a替换成A
    console.log(str.replace("a","A"));
    //只会将第一个匹配到的a替换成A。因为没有在全局范围内查找
    console.log(str.replace(/a/,"A"));
    //所有a都被替换成了A
    console.log(str.replace(/a/g,"A"));
</script>

replace基本用法之替换移除指定class类

<script type="text/JavaScript">
    /*要求将下面这个元素中的unabled类移除掉*/
    <div class=”confirm-btn unabled mb-10” id=”j_confirm_btn”>提交</div>
    var classname = document.getElementById(“j_confirm_btn”).className;
    /*(^|\\s)表示匹配字符串开头或字符串前面的空格,(\\s|$)表示匹配字符串结尾或字符串后面的空格*/
    var newClassName = classname.replace(/(^|\\s)unabled(\\s|$)/,””);
    document.getElementById(“j_confirm_btn”).className = newClassName;
</script>

2、replace高级用法之 ---- $i

2.1、简单的$i用法

<script>
    /*要求:将字符串中的双引号用"-"代替*/
    var str = &#39;"a", "b"&#39;;
    console.log(str.replace(/"[^"]*"/g,"-$1-"));
    //输出结果为:-$1-, -$1-
    /*解释:$1就是前面正则(/"[^"]*"/g)所匹配到的每一个字符。*/
</script>

2.2、$i与分组结合使用

<script>
    /*要求:将下面字符串替换成:JavaScript is fn.it is a good script language*/
    
    var str = "JavaScript is a good script language";
    console.log(str.replace(/(JavaScript)\s*(is)/g,"$1 $2 fn.it $2"));
    /*解释:每一对括号都代表一个分组,从左往右分别代表第一个分组,第二个分组...;如上"*(JavaScript)"为第一个分组,
"(is)"为第二个分组。$1就代表第一个分组匹配的内容,$2就代表第二个分组匹配的内容,依此类推...*/
</script>

2.3、$i与分组结合使用----关键字高亮显示

当我们使用谷歌搜索的时候我们会发现我们搜索的关键字都被高亮显示了,那么这种效果用JavaScript能否显示呢?答案是可以的,使用replace()很轻松就搞定了。

<script>
    /*要求:将下列字符串中的"java"用红色字体显示*/
    
    var str = "Netscape在最初将其脚本语言命名为LiveScript,后来Netscape在与Sun合作之后将其改名为JavaScript。
JavaScript最初受Java启发而开始设计的,目的之一就是“看上去像Java”,因此语法上有类似之处,一些名称和命名规范也借自Java。
但JavaScript的主要设计原则源自Self和Scheme。";
    document.write(str.replace(/(java)/gi,&#39;<span style="color: red;font-weight: 800;">$1</span>&#39;));
    /*解释:必须要开启全局搜索和忽略大小写,否则匹配不到所有的”java”字符*/
</script>

2.4、反向分组----分组的反向引用

在正则中,当我们需要匹配两个或多个连续的相同的字符的时候,就需要用到反向引用了,查找连续重复的字符是反向引用最简单却也是最有用的应用之一。上面的”$i”也是反向分组的一种形式,这里再介绍另一种反向分组。

<script type="text/javascript">
    /* /ab(cd)\1e/ 这里的 \1 表示把第1个分组的内容重复一遍*/
    console.log(/ab(cd)\1e/.test("abcde"));//false
    console.log(/ab(cd)\1e/.test("abcdcde"));//true
    /*要求:将下列字符串中相领重复的部分删除掉"*/
    var str = "abbcccdeee";
    var newStr = str.replace(/(\w)\1+/g,"$1");
    console.log(newStr); // abcde
</script>

3、replace高级用法之参数二为函数

replace函数的第二个参数不仅可以是一个字符,还可以是一个函数!

3.1、参数二为函数之参数详解

<script>
    var str = "bbabc";
    var newStr = str.replace(/(a)(b)/g,function (){
    console.log(arguments);//["ab", "a", "b", 2, "bbabc"]
     /*参数依次为:
        1、整个正则表达式所匹配到的字符串----"ab"
        2、第一个分组匹配到的字符串,第二个分组所匹配到的字符串....依次类推一直            到最后一个分组----"a,b"
        3、此次匹配在源字符串中的下标,返回的是第一个匹配到的字符的下标----2
        4、源字符串----"bbabc"
      */
    })
</script>

3.2、参数二为函数之首字母大写案例

<script>
    /*要求:将下列字符串中的所有首字母大写*/
    
    var str = "Tomorrow may not be better, but better tomorrow will surely come!";
    var newStr = str.replace(/\b\w+\b/gi,function (matchStr){
        console.log(matchStr);//匹配到的字符
        return matchStr.substr(0,1).toUpperCase() + matchStr.substr(1);
    });
    console.log(newStr);
</script>

3.3、参数二为函数之绑定数据----artTemplate模板核心

<h1 id="周星驰喜剧电影">周星驰喜剧电影:</h1>
<div id="content"></div>
<script type="text/javascript">
    var data = {
        name: "功夫",
        protagonist: "周星驰"
    },
    domStr = &#39;<div><span>名称:</span><span>{{name}}</span></div><div><span>导演:</span><span>{{protagonist}}</span> </div>&#39;;
    document.getElementById("content").innerhtml = formatString(domStr,data);
    /*绑定数据的核心就是使用正则进行匹配*/
    function formatString(str,data){
        return str.replace(/{{(\w+)}}/g,function (matchingStr,group1){
            return data[group1];
        });
    }
</script>

4、replace高级用法之获取与正则表达式匹配的文本

4.1、replace高级用法之获取与正则表达式进行匹配的源字符串

<script>
    var str = "i am a good man";
    var newStr = str.replace(/good/g,"$&");
    console.log(newStr);//结果:输出i am a good man
    /*解释:在这里”$&”就是与正则表达式进行匹配的那个源字符串*/
</script>

4.2、replace高级用法之获取正则表达式匹配到的字符

<script>
    /*要求:将"i am a good man"替换成"i am a good-gond man" */
    
    var str = "i am a good man";
    var newStr = str.replace(/good/g,"$&-$&");
    console.log(newStr);
    /*解释:在这里”$&”可以获取到前面正则表达式匹配的内容,如上面的”$&”就是正则表达式匹配到的”good”*/
</script>

5、replace高级用法之获取正则匹配的左边的字符

<script>
   /*要求:将下列字符串替换成"java-java is a good script"*/
    var str = "javascript is a good script";
    var newStr = str.replace(/script/,"-$`");
    console.log(newStr)
    /*解释:"$`"获取的是正则左边的内容,如上正则中"script"字符前面的是"java","-$`"就是"-java","-$`"会把script替换掉。*/
</script>

6、replace高级用法之获取正则匹配的右边的字符

<script>
     /*要求:将下列字符替换成"java is a good language!it is a good script is a good script"*/
     
    var str = "javascript is a good script";
    var newStr = str.replace(/script/," is a good language!it$&#39;");
    console.log(newStr)
    /*解释:"$&#39;"获取的就是str右边的内容,如上正则中"$&#39;"就是" is a good script"。
    " is a good language!it$&#39;"会把正则匹配到的"script"替换掉*/
</script>

推荐教程:《JavaScript视频教程》 

The above is the detailed content of How to replace string in js?. For more information, please follow other related articles on the PHP Chinese website!

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 in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

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 Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

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.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)