顯示廣告
隱藏 ✕
※ 本文為轉錄連結,轉錄者為 mesak
看板 Knuckles_note
作者 Knuckles (站長 那克斯)
標題 [JS] match, replace 使用 RegExp 正規表示式
時間 2013年04月25日 Thu. PM 11:40:56


○ .replace 字串取代的用法

直接取代已知的字串

例如將第一個 hello 換成 hi
replace_result = 'hello hello world'.replace('hello','hi');
console.log(replace_result); // "hi hello world"

改為正規表示式
origin_str = 'hello hello world';
replace_result = origin_str.replace(/hello/,'hi');
console.log(replace_result); // hi hello world

注意要用個變數來儲存 origin_str.replace(); 的輸出結果
只執行 origin_str.replace(); 的話 origin_str 的值不會改變

預設只會取代找到的第一個,如果要取代所有字串要加 /g

replace_result = 'hello hello world'.replace(/hello/g,'hi');
console.log(replace_result); // hi hi world

要忽略大小寫的話加 /i

replace_result = 'hello hello world'.replace(/HELLO/gi,'hi');
console.log(replace_result); // hi hi world


若正規表示式要用字串組出來的話

var str = 'hello hello world';
var regex = new RegExp('he'+'llo','gi');
var str2 = str.replace(regex,'hi!');


注意使用 new RegExp() 時,跳脫字元\要寫兩次,例如

var reg = new RegExp('\\d','g');


取代的字串若有 \ 要加跳脫字元,例如要把「sth」換成「\sth」的話

replace(/(sth)/g,'\\$1')


○ Single Line Option

Javascript不支援讓 . 也包含換行字元的 /s 選項
要取得所有字元含換行的話,要把 . 改成 [\s\S]


○ match 的用法

origin_str = 'hello hello world';
regex = /\w+/g;
M = origin_.match(regex);
console.log(M); // ["hello", "hello", "world"]

注意 match 輸入值若為一般字串,會被當成正規運算
而不像 replace 一樣可以直接找一般字串

例如: '[1234] [abc]'.match('[1234]'); // ["1"]
      '[1234] [abc]\w'.match('\\w');  // ["1"]


要單純尋找一個字串的話,要先把可能會出現的正規運算符號加上\

search_str = '[1234]';
search_str_escape = search_str.replace(/([\\\[\]\(\)\{\}\.\*\?\+\|\^\$])/g,'\\$1');
	

regex = new RegExp(search_str_escape); // /\[1234\]/
'[1234] [abc]'.match(regex); // ["[1234]"]


--
※ 作者: Knuckles 時間: 2013-04-25 23:40:56
※ 編輯: Knuckles 時間: 2023-01-07 02:12:21 (台灣)
※ 看板: Mesak 文章推薦值: 2 目前人氣: 0 累積人氣: 2188 
※ 本文也出現在看板: KnucklesNote
分享網址: 複製 已複製
( ̄︶ ̄)b moniliforme, mesak 說讚!
mesak 轉錄至看板 Mesak (使用連結) 時間:2014-09-03 01:11:23
r)回覆 e)編輯 d)刪除 M)收藏 ^x)轉錄 同主題: =)首篇 [)上篇 ])下篇