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

利用 .htaccess 限制可瀏覽ip來源

利用 .htaccess 限...

要如何限制某個資料夾內容只能給特定IP讀取? 這個部分其實可以透過.htaccess快速實現~ 首先...

PHP清空陣列函數

PHP清空陣列函數

pexelsphoto5555 unset(arrar) 將整個陣列清空,但之後如果再加入元素,其 ...

使用curl執行POST請求

使用curl執行POST請求...

curl命令是一個利用URL規則在命令行下工作的文件傳輸工具。 支持文件的上傳和下載。 這邊範例使用...

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