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

讓文字左右對齊

讓文字左右對齊

讓文字左右對齊這類的設計案,通常都會出現在平面設計居多。 網頁上很少會遇到客戶會執著於這方面,但不能...

js判斷字母是否為大小寫

js判斷字母是否為大小寫

使用JS來判斷字串裡是否含有大寫字母或小寫字母。 //判斷是否含有大寫字母 function chk...

javascript如何通過其 ID 設置選擇元素的選定選項?

javascript如何通過...

如題,透過javascript來針對某個select的option來做選定。 document.ge...

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