簡體   English   中英

使用正則表達式替換字符串中的多個字符

[英]Replace multiple characters in a string using regex

我想替換字符串中多個字符的多次出現。假設我有一個包含空格和/字符的字符串。 如何用_替換兩者?

我知道如何用replace()方法替換單個字符,如下所示:

var s = 'some+multi+word+string'.replace(/\+/g, ' ');

如何更新它以替換多個字符?

要捕獲多個連續字符,請使用正則表達式中的+運算符。 另請注意,要捕獲空格和斜杠,您可以在字符集中指定它們,例如[\s\/] 嘗試這個:

 var s = 'some multi///word/string'.replace(/[\s\/]+/g, '_'); console.log(s);

在列表中定義你的角色[]

 const r = "abc def/ //gh".replace(/[ \/]/g, "_"); console.log(r) // "abc_def____g_h"

要替換多個,請使用+量詞(出現一次或多次

 const r = "abc def/ //gh".replace(/[ \/]+/g, "_"); console.log(r) // "abc_def_g_h"

用“ _ ”替換確切的序列“ / ”(空格+ForwardSlash)

 const r = "abc /def /g /h".replace(/ \/+/g, "_"); console.log(r) // "abc_def_g_h"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM