Table of Contents
周星驰喜剧电影:
Home Web Front-end JS Tutorial How to replace string in js?

How to replace string in js?

Jul 28, 2020 am 11:45 AM
javascript string

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

How to replace string in js?

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

语法:

stringObject.replace(regexp/substr,replacement)
Copy after login

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>
Copy after login

输出:

hello!
Copy after login

扩展知识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>
Copy after login

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>
Copy after login

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

2.1、简单的$i用法

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

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

推荐教程:《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 of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed explanation of the method of converting int type to string in PHP Detailed explanation of the method of converting int type to string in PHP Mar 26, 2024 am 11:45 AM

Detailed explanation of the method of converting int type to string in PHP In PHP development, we often encounter the need to convert int type to string type. This conversion can be achieved in a variety of ways. This article will introduce several common methods in detail, with specific code examples to help readers better understand. 1. Use PHP’s built-in function strval(). PHP provides a built-in function strval() that can convert variables of different types into string types. When we need to convert int type to string type,

How to determine whether a Golang string ends with a specified character How to determine whether a Golang string ends with a specified character Mar 12, 2024 pm 04:48 PM

Title: How to determine whether a string ends with a specific character in Golang. In the Go language, sometimes we need to determine whether a string ends with a specific character. This is very common when processing strings. This article will introduce how to use the Go language to implement this function, and provide code examples for your reference. First, let's take a look at how to determine whether a string ends with a specified character in Golang. The characters in a string in Golang can be obtained through indexing, and the length of the string can be

How to repeat a string in python_python repeating string tutorial How to repeat a string in python_python repeating string tutorial Apr 02, 2024 pm 03:58 PM

1. First open pycharm and enter the pycharm homepage. 2. Then create a new python script, right-click - click new - click pythonfile. 3. Enter a string, code: s="-". 4. Then you need to repeat the symbols in the string 20 times, code: s1=s*20. 5. Enter the print output code, code: print(s1). 6. Finally run the script and you will see our return value at the bottom: - repeated 20 times.

How to check if a string starts with a specific character in Golang? How to check if a string starts with a specific character in Golang? Mar 12, 2024 pm 09:42 PM

How to check if a string starts with a specific character in Golang? When programming in Golang, you often encounter situations where you need to check whether a string begins with a specific character. To meet this requirement, we can use the functions provided by the strings package in Golang to achieve this. Next, we will introduce in detail how to use Golang to check whether a string starts with a specific character, with specific code examples. In Golang, we can use HasPrefix from the strings package

How to intercept a string in Go language How to intercept a string in Go language Mar 13, 2024 am 08:33 AM

Go language is a powerful and flexible programming language that provides rich string processing functions, including string interception. In the Go language, we can use slices to intercept strings. Next, we will introduce in detail how to intercept strings in Go language, with specific code examples. 1. Use slicing to intercept a string. In the Go language, you can use slicing expressions to intercept a part of a string. The syntax of slice expression is as follows: slice:=str[start:end]where, s

How to solve the problem of Chinese garbled characters when converting hexadecimal to string in PHP How to solve the problem of Chinese garbled characters when converting hexadecimal to string in PHP Mar 04, 2024 am 09:36 AM

Methods to solve Chinese garbled characters when converting hexadecimal strings in PHP. In PHP programming, sometimes we encounter situations where we need to convert strings represented by hexadecimal into normal Chinese characters. However, in the process of this conversion, sometimes you will encounter the problem of Chinese garbled characters. This article will provide you with a method to solve the problem of Chinese garbled characters when converting hexadecimal to string in PHP, and give specific code examples. Use the hex2bin() function for hexadecimal conversion. PHP’s built-in hex2bin() function can convert 1

PHP String Matching Tips: Avoid Ambiguous Included Expressions PHP String Matching Tips: Avoid Ambiguous Included Expressions Feb 29, 2024 am 08:06 AM

PHP String Matching Tips: Avoid Ambiguous Included Expressions In PHP development, string matching is a common task, usually used to find specific text content or to verify the format of input. However, sometimes we need to avoid using ambiguous inclusion expressions to ensure match accuracy. This article will introduce some techniques to avoid ambiguous inclusion expressions when doing string matching in PHP, and provide specific code examples. Use preg_match() function for exact matching In PHP, you can use preg_mat

PHP string manipulation: a practical way to effectively remove spaces PHP string manipulation: a practical way to effectively remove spaces Mar 24, 2024 am 11:45 AM

PHP String Operation: A Practical Method to Effectively Remove Spaces In PHP development, you often encounter situations where you need to remove spaces from a string. Removing spaces can make the string cleaner and facilitate subsequent data processing and display. This article will introduce several effective and practical methods for removing spaces, and attach specific code examples. Method 1: Use the PHP built-in function trim(). The PHP built-in function trim() can remove spaces at both ends of the string (including spaces, tabs, newlines, etc.). It is very convenient and easy to use.

See all articles