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

Android UI設計距離課題

Android UI設計距離...

layoutmarginTop指定該屬性所在控件距離上方的位置空間。 layoutmarginBot...

判斷字串是否存在於內容中

判斷字串是否存在於內容中

searchphoto5 以下範例~ 搜尋 If you are lucky enough to b...

使用jQuery阻止input直接按Enter就送出表單

使用jQuery阻止inpu...

使用表單是傳送資料裡經常會用到的方式。 這時當使用者輸入表單後習慣上按下Enter,則會將表單內容送...

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