search
HomeWeb Front-endJS TutorialHow to use replace function in javascript

How to use replace function in javascript

Jun 13, 2018 pm 02:26 PM
jsreplacefunction

在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
//当第一个参数是一个简单字符串时,仅替换第一个匹配项

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字符串都将被替换

忽略大小写匹配:

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

忽略大小写且全局匹配:

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

使用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返回的内容

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

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

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

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

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

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

使用正则表达式对象:

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

有了这些例子 加上开头的名词解释,相信你已经彻底搞懂了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
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: 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.

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

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 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

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.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use