JS中字符串的替換操作是開發中常用的操作之一。替換操作之所以重要,是因為字符串在實際開發中是非常常見的一種數據類型。無論是前端還是後端,我們都需要進行字符串的替換操作。
一、JS替換字符串指定字符
// 示例代碼 const str = "this is a test string for replace operations" const newStr = str.replace("t", "T") console.log(newStr) // 輸出:This is a Test sTring for replace operations
在JS中有一種string類型中原生的replace方法,我們可以使用這個方法來進行替換操作。上面的示例中,我們將字符串中的第一個 “t” 替換成了 “T”。
二、JS替換字符串中所有中文
// 示例代碼 const str = "這是一個測試用的中文字符串" const newStr = str.replace(/[\u4e00-\u9fa5]+/g, "***") console.log(newStr) // 輸出:***測試用的***字符串
如果要將字符串中所有中文替換為指定字符,可以使用正則表達式中的 Unicode 值來進行匹配。上面的示例中,我們使用正則表達式找到了 Unicode 值在 4E00 到 9FA5 之間的字符,然後將所有中文字符替換成了三個星號。
三、JS替換字符串中文
// 示例代碼 const str = "this is a 中文 testing string" const newStr = str.replace(/中文/g, "***") console.log(newStr) // 輸出:this is a *** testing string
如果要將指定中文替換為指定字符,也可以使用正則表達式。上面的示例中,我們使用中文關鍵詞 “中文” 進行替換操作,將其替換為三個星號。
四、JS替換字符串中的字符
// 示例代碼 const str = "this is a test string for replace operations" const newStr = str.replace(/t/g, "T") console.log(newStr) // 輸出:This is a TesT sTring for replace operaTions
如果要將字符串中所有指定字符替換為指定字符,同樣可以使用正則表達式。上面的示例中,我們使用正則表達式查找所有字符 “t” 並替換成了 “T”。
五、JS替換字符串所有逗號
// 示例代碼 const str = "this,is,a,test,string,for,replace,operations" const newStr = str.replace(/,/g, " ") console.log(newStr) // 輸出:this is a test string for replace operations
如果要將字符串中的所有逗號替換為指定字符,同樣可以使用正則表達式。上面的示例中,我們使用正則表達式查找所有逗號並替換成了空格。
六、JS替換字符串指定內容
// 示例代碼 const str = "this is a test string for replace operations" const newStr = str.replace("test", "TEST") console.log(newStr) // 輸出:this is a TEST string for replace operations
除了使用正則表達式進行字符串匹配外,也可以使用普通的字符串來進行匹配。上面的示例中,我們將字符串中的單詞 “test” 替換成了 “TEST”。
七、JS替換字符串中全局的0
// 示例代碼 const str = "this is a test string with 0, 1, 2 and 3" const newStr = str.replace(/0/g, "ZERO") console.log(newStr) // 輸出:this is a test string with ZERO, 1, 2 and 3
如果要將字符串中的所有指定字符替換為指定字符,同樣可以使用正則表達式。上面的示例中,我們使用正則表達式查找所有數字 “0” 並替換成了 “ZERO”。
八、JS替換字符串中所有逗號
// 示例代碼 const str = "this,is,a,test,string,for,replace,operations" const newStr = str.replace(/,/g, " ") console.log(newStr) // 輸出:this is a test string for replace operations
如果要將字符串中的所有逗號替換為指定字符,同樣可以使用正則表達式。上面的示例中,我們使用正則表達式查找所有逗號並替換成了空格。
九、JS字符串替換第幾位
// 示例代碼 const str = "this is a test string for replace operations" const newStr = str.substring(0, 5) + "was" + str.substring(8) console.log(newStr) // 輸出:this was a test string for replace operations
對於需要替換某一個特定字符的場景,我們可以使用字符串自身的方法來實現。上面的示例中,我們直接使用JS的substring方法,找到需要替換的字符並進行替換操作。
十、JS字符串替換全部
// 示例代碼 const str = "this is a test string with multiple test words" const newStr = str.split("test").join("TEST") console.log(newStr) // 輸出:this is a TEST string with multiple TEST words
如果要將字符串中所有指定字符串都替換為指定字符串,也可以使用字符串自身的方法。上面的示例中,我們使用split和join方法來將字符串中所有 “test” 替換成了 “TEST”。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/193497.html