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

PDO bindParam 和 bindValue 差別在哪裡?

PDO bindParam ...

首先 bindParam 是綁定變數、bindValue  是綁定值。 以下範例: bindPara...

PHP輸出到WORD跟EXCEL 簡易做法

PHP輸出到WORD跟EXC...

pexelsphotooffice WORD: $filename="test.doc&q...

javascript如何取得檔案的副檔名?

javascript如何取得...

var filenamea = "aaa"; alert(getFileExte...

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