- Q
replace() 1
- 如何使用 replace() 來替換字符串中的字符。
- replace() 2 - 全局搜索
- 如何使用 replace() 進行全局替換。
- replace() 3 - 對大小寫不敏感的搜索
- 如何使用 replace() 確保大寫字母的正確性。
- replace() 4
- 如何使用 replace() 來轉換姓名的格式。
- replace() 5
- 如何使用 replace() 來轉換引號。
- replace() 6
- 如何使用 replace() 把單詞的首字母轉換為大寫。
實例
例子 1
在本例中,我們將使用 "W3School" 替換字符串中的 "Microsoft":
<script type="text/javascript">
var str="Visit Microsoft!"
document.write(str.replace(/Microsoft/, "W3School")
)
</script>
輸出:
Visit W3School!
例子 2
在本例中,我們將執行一次全局替換,每當 "Microsoft" 被找到,它就被替換為 "W3School":
<script type="text/javascript">
var str="Welcome to Microsoft! "
str=str + "We are proud to announce that Microsoft has "
str=str + "one of the largest Web Developers sites in the world."
document.write(str.replace(/Microsoft/g, "W3School")
)
</script>
輸出:
Welcome to W3School! We are proud to announce that W3School
has one of the largest Web Developers sites in the world.
例子 3
您可以使用本例提供的代碼來確保匹配字符串大寫字符的正確:
text = "javascript Tutorial";
text.replace(/javascript/i, "JavaScript");
例子 4
在本例中,我們將把 "Doe, John" 轉換為 "John Doe" 的形式:
name = "Doe, John";
name.replace(/(\w+)\s*, \s*(\w+)/, "$2 $1");
例子 5
在本例中,我們將把所有的花引號替換為直引號:
name = '"a", "b"';
name.replace(/"([^"]*)"/g, "'$1'");
例子 6
在本例中,我們將把字符串中所有單詞的首字母都轉換為大寫:
name = 'aaa bbb ccc';
uw=name.replace(/\b\w+\b/g, function(word){
return word.substring(0,1).toUpperCase()+word.substring(1);}
);