如何使用JavaScript替換字串的一部分為另一個值?
在本文中,我們將探討如何使用JavaScript替換字串的一部分為另一個值。我們可以透過多種方式替換字串部分。以下是一些常用的方法:
replace() 方法
split() 方法
join() 方法
讓我們詳細討論以上方法。
replace() 方法
這是JavaScript提供的一個內建方法,允許使用者將字串的一部分替換為另一個字串或正則表示式。但是,原始字串將保持不變。
語法
string.replace(searchvalue, newvalue)
引數
searchvalue - 用於在整個字串中搜索字串。
newvalue - 將替換搜尋到的字串。
該函式將返回一個新的字串作為此方法的輸出。
示例1
在下面的示例中,我們將使用JavaScript replace() 方法將“Hi”替換為“Welcome To”。
# index.html
<html> <head> <title>Replacing String</title> </head> <body> <h1 style="color: green;"> Welcome To Tutorials Point </h1> <script> let string = "Hi Tutorials Point"; /* It will search for Hi and then replace it with the another string */ let replaced_string = string.replace("Hi", "Welcome To"); document.write('<h4>The original string is:</h4>' +string); document.write('<h4>The replaced string is:</h4>' +replaced_string); </script> </body> </html>
輸出
split() 方法
我們還可以使用split() 方法將字串拆分為子字串陣列。一旦字串轉換為陣列,我們就可以將每個字串與要搜尋的字串進行比較。找到字串後,我們將用新字串替換它。字串split() 方法接受一個分隔符,我們將用它來分割字串。
string.split(separator,limit)
join() 方法
join() 方法用於連線陣列元素並將其作為字串返回。此方法只有一個可選引數。
array.join(separator)
示例2
# index.html
<html> <head> <title>Replacing String</title> </head> <body> <h1 style="color: green;"> Welcome To Tutorials Point </h1> <script> let string = "Start Learning the latest technologies courses now."; let replaced_string = string.split("technologies").join("java"); document.write("<h4>The replaced string is: </h4> " + replaced_string); document.write("<h4>The original string is: </h4>" + string); </script> </body> </html>
輸出
廣告