String.replace( ) 簡介
文法:
string.replace(regexp, replacement)
regexp :您要執行替換操作的Regex,如果傳入的是一個字串,那就會當作一般字元來處理,並且只會執行一次替換操作;如果是Regex,並且帶有 global (g) 修飾符,則會替換所有出現的目標字元,否則,將只執行一次替換操作。
replacement :您要替換成的字元。
傳回值是執行替換操作後的字串。
String.replace( ) 的簡單用法
var text = "javascript 非常強大 !";text.replace(/javascript/i, "JavaScript");// 返回:JavaScript 非常強大 !
String.replace( ) 替換所有出現的目標字元
var text= "javascript 非常強大 !JAVASCRIPT 是我最喜歡的一門語言 !";text.replace(/javascript/ig, "JavaScript");// 返回:JavaScript 非常強大 !JavaScript 是我最喜歡的一門語言 !
String.replace( ) 實現調換位置
var name= "Doe, John";name.replace(/(\w+)\s*,\s*(\w+)/, "$2 $1");// 返回:John Doe
String.replace( ) 實現將所有雙引號包含的字元替換成中括弧包含的字元
var text = '"JavaScript" 非常強大!';text.replace(/"([^"]*)"/g, "[$1]");// 返回:[JavaScript] 非常強大!
String.replace( ) 將所有字元首字母大寫
var text = 'a journey of a thousand miles begins with single step.';text.replace(/\b\w+\b/g, function(word) { return word.substring(0,1).toUpperCase( ) + word.substring(1); });// 返回:A Journey Of A Thousand Miles Begins With Single Step.
以上轉自:http://www.codebit.cn/javascript/javascript-replace.html
String.replace() 參數解釋
當第一個參數為Regex時,第二個參數為一個function時,第二個參數中的function的參數中 $表示正則匹配的字串,$1,$2...為分組的內容:
"abc {name} test".replace(/{(.*?)}/img,function($,$1){ console.log($,$1);//output {name} name return $1;});