Home Web Front-end JS Tutorial How to use replace function in javascript

How to use replace function in javascript

Jun 13, 2018 pm 02:26 PM
js replace function

在js中有两个replace函数 一个是location.replace(url) 跳转到一个新的url.一个string.replace("xx","yy") 替换字符串 返回一个新的字符串,该方法并不改变字符串本身。下面通过本文给大家介绍javascript中的replace函数

javascript这门语言一直就像一位带着面纱的美女,总是看不清,摸不透,一直专注服务器端,也从来没有特别重视过,直到最近几年,javascript越来越重要,越来越通用。最近和前端走的比较近,借此机会,好好巩固一下相关知识点。

1.初识replace

在js中有两个replace函数 一个是location.replace(url) 跳转到一个新的url

一个string.replace("xx","yy") 替换字符串 返回一个新的字符串,该方法并不改变字符串本身

location.replace(url) 无痕跳转(将当前链接导航到一个新的url 并不保存历史记录)
与之相对的是location.href="url" rel="external nofollow" 有痕跳转(将当前链接导航到一个新的url 且保存历史记录) 这个没有比较清晰

string.replace函数 很多初学者,会认为这个跟C#中的Replace一样,但并不相同,js中replace更灵活。
最基本的用法 就是简单替换字符串。来看一个例子:

var str = "abcd-abcd-abcd";
var result = str.replace("a", "");
console.log(result);
//输出 bcd-abcd-abcd
//当第一个参数是一个简单字符串时,仅替换第一个匹配项
Copy after login

2.走进replace之正则表达式

参数一:正则表达式对象或字面量(支持gi模式) g全局匹配 i忽略大小写

参数二:要替换的字符串或一个function

可以使用正则表达式的相关引用

如果是function,则替换为function的返回值

此function的参数:

match 匹配的子串。(对应于上述的$&。)

p1,p2, ... 假如replace()方法的第一个参数是一个RegExp 对象,则代表第n个括号匹配的字符串。(对应于上述的$1,$2等。)

offset 匹配到的子字符串在原字符串中的偏移量。(比如,如果原字符串是“abcd”,匹配到的子字符串是“bc”,那么这个参数将是1)

string 被匹配的原字符串。

正则表达的引用

$$ 插入一个 "$"。
$& 插入匹配的子串。
$` 插入当前匹配的子串左边的内容。
$' 插入当前匹配的子串右边的内容。
$n 假如第一个参数是 RegExp对象,并且 n 是个小于100的非负整数,那么插入第 n 个括号匹配的字符串。

3.来一轮带注释的demo,彻底搞懂javascript中的replace函数:

全局匹配:

var str = "abcd-abcd-abcd";
var result = str.replace(/a/g, "e");
console.log(result);
//输出 ebcd-ebcd-ebcd
//g全局匹配 所有a字符串都将被替换
Copy after login

忽略大小写匹配:

var str = "abcd-abcd-abcd";
var result = str.replace(/A/i, "e");
console.log(result);
// 输出 ebcd-abcd-abcd
// 忽略大小写的匹配 但没有进行全局匹配 所以只替换第一个a
Copy after login

忽略大小写且全局匹配:

var str = "abcd-abcd-abcd";
var result = str.replace(/A/gi, "e");
console.log(result);
// 输出 ebcd-ebcd-ebcd
// 忽略大小写并全局匹配 所有a都被替换
Copy after login

使用function作为第二参数:

var str = "abcd-abcd-1234";
var result = str.replace(/([a-z]*)-([a-z]*)/gi, function(match,p1,p2,offset,str){
  console.log(match);  //abcd-abcd 匹配的内容
  console.log(p1);  //第一个括号中匹配的内容
  console.log(p2);  //第二个括号匹配的内容
  console.log(offset);//0 匹配到的字符串的索引(偏移量) 
  console.log(str);  //原始字符串
  return [p1,p2].join("+");
});
console.log(result);
// 输出 abcd+abcd+1234
// 原字符串中 abcd-abcd 被匹配后 被替换为function返回的内容
Copy after login

在参数中引用正则表达式匹配项:

var str = "a b";
var result = str.replace(/(\w+)\s(\w+)/gi, "$2 $1");
console.log(result); 
//输出 b a 
// 这里的$1 $2分别引用正则表达式中第一个喝第二个括号匹配的内容
Copy after login

在参数中引用匹配项左侧内容:

 var str = 'abc';
  var result = str.replace(/b/g, "$`"); //$`代表匹配字符的左侧内容
  console.log(result);
  //输出: aac
Copy after login

在参数中引用匹配项右侧内容:

 var str = 'abc';
  var result = str.replace(/b/g, "$'"); //$'代表匹配字符的右侧内容
  console.log(result);
  //输出: acc
Copy after login

使用正则表达式对象:

 var str = "a b";
 var reg = new RegExp(/(\w+)\s(\w+)/, "gi"); //也可以使用正则表示对象来最为参数
 var result = str.replace(reg, "$2 $1");
 console.log(result); //输出 b a
Copy after login

有了这些例子 加上开头的名词解释,相信你已经彻底搞懂了javascript中的replace函数!

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

详细解读AngularJS中$window窗口对象的概念

React-native桥接Android如何实现,具体步骤又是什么?

在vue中如何开发自定义指令directive

移动web开发中有关touch事件(详细教程)

详细解读layui父子窗口如何传递参数

The above is the detailed content of How to use replace function in javascript. 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)

Tips for dynamically creating new functions in golang functions Tips for dynamically creating new functions in golang functions Apr 25, 2024 pm 02:39 PM

Go language provides two dynamic function creation technologies: closure and reflection. closures allow access to variables within the closure scope, and reflection can create new functions using the FuncOf function. These technologies are useful in customizing HTTP routers, implementing highly customizable systems, and building pluggable components.

Considerations for parameter order in C++ function naming Considerations for parameter order in C++ function naming Apr 24, 2024 pm 04:21 PM

In C++ function naming, it is crucial to consider parameter order to improve readability, reduce errors, and facilitate refactoring. Common parameter order conventions include: action-object, object-action, semantic meaning, and standard library compliance. The optimal order depends on the purpose of the function, parameter types, potential confusion, and language conventions.

How to write efficient and maintainable functions in Java? How to write efficient and maintainable functions in Java? Apr 24, 2024 am 11:33 AM

The key to writing efficient and maintainable Java functions is: keep it simple. Use meaningful naming. Handle special situations. Use appropriate visibility.

Complete collection of excel function formulas Complete collection of excel function formulas May 07, 2024 pm 12:04 PM

1. The SUM function is used to sum the numbers in a column or a group of cells, for example: =SUM(A1:J10). 2. The AVERAGE function is used to calculate the average of the numbers in a column or a group of cells, for example: =AVERAGE(A1:A10). 3. COUNT function, used to count the number of numbers or text in a column or a group of cells, for example: =COUNT(A1:A10) 4. IF function, used to make logical judgments based on specified conditions and return the corresponding result.

Comparison of the advantages and disadvantages of C++ function default parameters and variable parameters Comparison of the advantages and disadvantages of C++ function default parameters and variable parameters Apr 21, 2024 am 10:21 AM

The advantages of default parameters in C++ functions include simplifying calls, enhancing readability, and avoiding errors. The disadvantages are limited flexibility and naming restrictions. Advantages of variadic parameters include unlimited flexibility and dynamic binding. Disadvantages include greater complexity, implicit type conversions, and difficulty in debugging.

What are the benefits of C++ functions returning reference types? What are the benefits of C++ functions returning reference types? Apr 20, 2024 pm 09:12 PM

The benefits of functions returning reference types in C++ include: Performance improvements: Passing by reference avoids object copying, thus saving memory and time. Direct modification: The caller can directly modify the returned reference object without reassigning it. Code simplicity: Passing by reference simplifies the code and requires no additional assignment operations.

What is the difference between custom PHP functions and predefined functions? What is the difference between custom PHP functions and predefined functions? Apr 22, 2024 pm 02:21 PM

The difference between custom PHP functions and predefined functions is: Scope: Custom functions are limited to the scope of their definition, while predefined functions are accessible throughout the script. How to define: Custom functions are defined using the function keyword, while predefined functions are defined by the PHP kernel. Parameter passing: Custom functions receive parameters, while predefined functions may not require parameters. Extensibility: Custom functions can be created as needed, while predefined functions are built-in and cannot be modified.

C++ Function Exception Advanced: Customized Error Handling C++ Function Exception Advanced: Customized Error Handling May 01, 2024 pm 06:39 PM

Exception handling in C++ can be enhanced through custom exception classes that provide specific error messages, contextual information, and perform custom actions based on the error type. Define an exception class inherited from std::exception to provide specific error information. Use the throw keyword to throw a custom exception. Use dynamic_cast in a try-catch block to convert the caught exception to a custom exception type. In the actual case, the open_file function throws a FileNotFoundException exception. Catching and handling the exception can provide a more specific error message.

See all articles