search
HomeWeb Front-endJS TutorialIs javascript replace() case-insensitive?

Is javascript replace() case-insensitive?

Nov 04, 2021 pm 03:37 PM
javascriptreplace()not case sensitivereplace string

In JavaScript, the replace() function can use regular expressions to replace strings in a case-insensitive manner, the syntax is "string.replace(/value to be found/gi,"replacement value")"; Where "g" stands for global replacement and "i" stands for ignoring case.

Is javascript replace() case-insensitive?

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

In JavaScript, the replace() function can replace strings in a case-insensitive manner, which requires the help of regular expressions.

Thereplace() method is used to replace some characters with other characters in a string, or replace a substring that matches a regular expression.

Syntax:

string.replace(searchvalue,newvalue)
Parameters Description
searchvalue is required. A RegExp object that specifies the substring or pattern to be replaced.
Note that if the value is a string, it is retrieved as a literal literal pattern rather than first being converted to a RegExp object.
newvalue Required. A string value. Specifies functions for replacing text or generating replacement text.

Return value: a new string obtained by replacing the first match or all matches of regexp with replacement. The second parameter of the

replace() method can use a function. The function will be called when there is a match. The return value of the function will be used as the replacement text. At the same time, the function can receive $ as the second parameter. A prefix of special characters used to reference information related to the matched text.

Special characters in the second parameter of the replace() method
Conventional string Description
$1, $2, ..., $99 Text matching the 1st to 99th subexpressions in the regular expression
$& (Dollar sign hyphen) Substring matching the regular expression
$' (Dollar sign toggle skill key) is located Matches the text on the left side of the substring
$' (dollar sign single quote) Matches the text on the right side of the string
$$ means $ string

示例1

将字符串中的字符 a(不区分大小写) 替换为 x

<p>
将字符串中的字符 a(不区分大小写) 替换为 x
</p>
<p id="demo"></p>

<script>
var sText = "abcdefaABC";
//g 代表全局替换  i 代表 忽略大小写
var txt = sText.replace( /a/gi , &#39;x&#39;);
document.getElementById("demo").innerHTML = txt;
</script>

输出结果:

Is javascript replace() case-insensitive?

示例2

下面代码把字符串中每个单词转换为首字母大写形式显示。

var s = &#39;javascript is script , is not java.&#39;;  //定义字符串
//定义替换文本函数,参数为第一个子表达式匹配文本
var f = function ($1) {
    //把匹配文本的首字母转换为大写
    return $1.substring(0,1).toUpperCase() + $1.substring(1).toLowerCase();}
var a = s.replace(/(\b\w+\b)/g, f);  //匹配文本并进行替换
console.log(a);  //返回字符串“JavaScript Is Script , Is Not Java.”

在上面示例中替换函数的参数为特殊字符“$1”,它表示正则表达式 /(\b\w+\b)/ 中小括号匹配的文本,然后在函数结构内对这个匹配文本进行处理,截取其首字母并转换为大写形式,余下字符全为小写,然后返回新处理的字符串。replace() 方法是在原文本中使用这个返回的新字符串替换掉每次匹配的子字符串。

示例3

对于上面的示例还可以进一步延伸,使用小括号来获取更多匹配信息。例如,直接利用小括号传递单词的首字母,然后进行大小写转换处理,处理结果都是一样的。

var s = &#39;javascript is script , is not java.&#39;;  //定义字符串
var f = function ($1,$2,$3) {  //定义替换文本函数,请注意参数的变化
    return $2.toUpperCase() + $3;
}
var a = s.replace(/(\b\w+\b)/g, f);
console.log(a);

在函数 f() 中,第一个参数表示每次匹配的文本,第二个参数表示第一个小括号的子表达式所匹配的文本,即单词的首字母,第二个参数表示第二个小括号的子表达式所匹配的文本。

replace() 方法的第二个参数是一个函数,replace() 方法会给它传递多个实参,这些实参都包含一定的意思,具体说明如下:

  • 第一个参数表示与匹配模式相匹配的文本,如上面示例中每次匹配的单词字符串。

  • 其后的参数是与匹配模式中子表达式相匹配的字符串,参数个数不限,根据子表达式数而定。

  • 后面的参数是一个整数,表示匹配文本在字符串中的下标位置。

  • 最后一个参数表示字符串自身。

示例4

把上面示例中替换文本函数改为如下形式。

var f = function() {
    return arguments[1].toUpperCase() + arguments[2];
}

也就是说,如果不为函数传递形参,直接调用函数的 arguments 属性同样能够读取到正则表达式中相关匹配文本的信息。其中:

  • arguments[0]:表示每次匹配的文本,即单词。

  • arguments[1]:表示第一个子表达式匹配的文本,即单词的首个字母。

  • arguments[2]:表示第二个子表达式匹配的文本,即单词的余下字母。

  • arguments[3]:表示匹配文本的下标位置,如第一个匹配单词“javascript”的下标位置就是0,以此类推。

  • arguments[4]:表示要执行匹配的字符串,这里表示“javascript is script , is not java.”。

示例5

下面代码利用函数的 arguments 对象主动获取 replace() 方法的第一个参数中正则表达式所匹配的详细信息。

var s = &#39;javascript is script , is not java.&#39;;  //定义字符串
var f = function () {
    for (var i = 0; i < arguments.length; i++) {
        console.log("第" + (i + 1) + "个参数的值:"+ arguments[i]);
    }
    console.log("-----------------------------");
}
var a = s.replace(/(\b\w+\b)/g, f);

在函数结构体中,使用 for 循环结构遍历 arguments 属性时,发现每次匹配单词时,都会弹出 5 次提示信息,分别显示上面所列的匹配文本信息。其中,arguments[1]、arguments[2] 会根据每次匹配文本的不同,分别显示当前匹配文本中子表达式匹配的信息,arguments[3] 显示当前匹配单词的下标位置。而 arguments[0] 总是显示每次匹配的单词,arguments[4] 总是显示被操作的字符串。

【推荐学习:javascript高级教程

The above is the detailed content of Is javascript replace() case-insensitive?. 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
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.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

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

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.