自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

JavaScript 中替換字符串的幾種方法

開發(fā) 前端
替換字符串中的文本是 JavaScript 開發(fā)中的常見任務。本文研究幾種用 replace 和正則表達式替換文本的方法。

替換字符串中的文本是 JavaScript 開發(fā)中的常見任務。本文研究幾種用 replace 和正則表達式替換文本的方法。

[[346819]]

替換單個字串通常 JavaScript 的 String replace() 函數(shù)只會替換它在字符串中找到的第一個匹配的子符:

  1. const myMessage = 'this is the sentence to end all sentences'
  2. const newMessage = myMessage.replace('sentence', 'message'); 
  3. console.log(newMessage); // this is the message to end all sentences 

在這個例子中,僅替換了第一個 sentence 字串。

替換多個子串

如果希望 JavaScript 能夠替換所有子串,必須通過 /g 運算符使用正則表達式:

  1. const myMessage = 'this is the sentence to end all sentences'
  2. const newMessage = myMessage.replace(/sentence/g, 'message'); 
  3. console.log(newMessage); // this is the message to end all messages 

這一次次兩個子串都會被替換。

除了使用內聯(lián) /g 之外,還可以使用 RegExp 對象的構造函數(shù):

  1. const myMessage = 'this is the sentence to end all sentences'
  2. const newMessage = myMessage.replace(new RegExp('sentence', 'g'), 'message'); 
  3. console.log(newMessage); // this is the message to end all messages``` 

替換特殊字符

要替換特殊字符,例如 -/\^$*+?.()|[]{}),需要使用反斜杠對其轉義。

如果給定字符串 this\-is\-my\-url,要求把所有轉義的減號( \-)替換為未轉義的減號(-)。

可以用 replace() 做到:

  1. const myUrl = 'this\-is\-my\-url'
  2. const newUrl = myMessage.replace(/\\-/g, '-'); 
  3. console.log(newUrl); // this-is-my-url 

或者用new Regexp():

  1. const myUrl = 'this\-is\-my\-url'
  2. const newUrl = myUrl.replace(new RegExp('\-', 'g'), '-'); 
  3. console.log(newUrl); // this-is-my-url 

在第二個例子中不必用反斜杠來轉義反斜杠。

 

責任編輯:趙寧寧 來源: 前端先鋒
相關推薦

2020-08-01 16:19:13

JavaScript字符串開發(fā)

2024-07-22 15:42:08

Linux字符串

2020-09-03 10:13:49

JavaScript字符串pad

2020-06-23 14:51:13

JavaScript字符字符串

2010-06-03 08:55:43

LINQ

2009-11-30 18:26:06

PHP字符串替換

2009-08-06 17:24:08

C#字符串

2021-03-02 12:29:34

字符串函數(shù)

2020-08-24 08:05:47

JavaScriptJavaScript 頁面

2024-10-28 15:33:52

2011-07-11 16:00:22

字符串拼接

2015-06-09 14:43:36

javascript操作字符串

2010-07-14 16:37:33

SQL Server拆

2023-08-25 16:37:08

Pandas測試

2010-11-22 12:04:09

MySQL字段

2025-04-27 10:02:50

JavaScript前端開發(fā)

2010-09-02 10:02:17

PHP

2021-03-08 09:32:04

Python文件命令

2010-02-02 18:01:47

C++字符串替換函數(shù)

2009-10-12 10:33:11

Javascript替
點贊
收藏

51CTO技術棧公眾號