DIV CSS 佈局教程網

JavaScript replace() 字串替換方法詳解
編輯:JavaScript綜合知識     

方法用途

replace() 會找出符合正則表達式或指定字串的內容,並替換成新的子字串。若要全域替換,可使用 g 標記;若要忽略大小寫,可加上 i 標記。

語法

string.replace(regexp, newSubStr)
string.replace(substr, newSubStr)

基本替換

const re = /apples/gi;
const str = 'Apples are round, and apples are juicy.';

console.log(str.replace(re, 'oranges'));

使用捕獲群組調換內容

const re = /(w+)s(w+)/;
const str = 'zara ali';

console.log(str.replace(re, '$2, $1'));

這個範例會把两个單字前後調換,輸出為「ali, zara」。replace() 也可傳入函式,讓替換內容依比對結果動態產生。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved