Loading...

JavaScript 搜尋字串並取代

Temperature: 0 °C

Mark ChangMark Chang
author_tools

在 JavaScript 做搜尋並取代字串可以使用 replace()
replace() 適用於在字符串中用一些字符替換另一些字符,或替換一個與正則表達式匹配的子串。
例如:

var string = "Hello Word!";
var result = string.replace("Word", "Excel");

上面的 string 變數是 “Hello Word!”, 而變數 result 會變成 “Hello Excel!”
但是上列方式會有一個問題是, 他只會取代第一個符合條件的字串。
意思是說如果字串為Hello Word! Word!
那麼若使用上列例子得到的會是Hello Excel! Word!
因此,如果要取代掉整篇內容裡的相同字串,則必須使用下列方式:
var string = "Hello Word! Word!";
var result = string.replace(new RegExp('Word', 'g'), 'Excel');

以上,紀錄。

 

https://innstory.com/story-JavaScript_搜尋字串並取代-2301
javascript

Prev
 想在網頁上預覽PDF可使用的方案

Next
Linux_vi修改文件時遇到:E212無法打開文件進行寫入 

About the Author

Mark Chang

離不開電腦的宅男

Visitor message

Leave some footprints to prove that you visited me

Recommended reading

Author's other related stories

刪除已上傳至server的檔案

刪除已上傳至server的檔...

a5 管理系統,難免都會遇到要更新或刪除已經上傳到server的檔案。 總不能只是重新上傳卻又不把舊...

分享 斜槓青年正夯,什麼都會才是王道?他舉賈伯斯、巴菲特為例,勸你萬萬不可跨領域-風傳媒

分享 斜槓青年正夯,什麼都會...

巴菲特:「了解自己的能力圈,待在裡面。這個圈圈到底有多大其實無關緊要。知道圈圈的邊線究竟在哪則非常重...

當XAMPP遇到VMWARE占用PORT 443導致無法啟動APACHE

當XAMPP遇到VMWARE...

在使用XAMPP時,若系統有安裝 VMWare Workstation,VMWare會將 port ...

Please select an option

error

Hi, thank you for your participation, but you cannot vote repeatedly~

Join innstory now and start recording your story.

"Innstory" is a place to store stories. We are committed to becoming a warm platform. Deepening the bonds between people is our direction.
We are convinced that the blockchain between people is not just a cold calculation. Join us now.

Wrong format