本指南演示瞭如何使用jQuery從字符串中刪除子字符串。 這些示例利用了jQuery的grep()
函數,提供了一種類似於PHP的子字符串操作功能的靈活方法。 使用Firebug或您的瀏覽器的開發人員工具對代碼進行測試和實驗。
(function($) { var myFruits = "Apples, Bananas, Mangos, Blackberries, Oranges"; myFruits = myFruits.replace(/bMangos(, |$)/gi, ""); myFruits = "Apples, Bananas, Mangos, Blackberries, Oranges"; var result = $.grep(myFruits.split(', '), function(v) { return v != "Mangos"; }).join(', '); console.log(result); function filterOut(my_str, t) { //string, term return $.grep(my_str.split(', '), function(v) { return v != t; }).join(', '); } })(jQuery); //output: Apples, Bananas, Blackberries, Oranges
> jQuery字符串操縱上的常見問題(常見問題解答) 本節解決了有關操縱jQuery中的字符串的常見問題。
>>
問:如何使用jQuery從字符串中刪除特定字符?a:>使用
>方法。 例如:
replace()
問:如何刪除字符的多個實例?
var str = "Hello, World!"; str = str.replace(",", ""); // Removes the comma
>在>方法的正則表達式中使用全局標誌():
Q:如何刪除子字符串?
g
>replace()
a:
var str = "Hello, World, Hello!"; str = str.replace(/,/g, ""); // Removes all commas
方法也適用於子字符串:>
問:如何刪除case-insensitionally?
>a:replace()
>使用案例不敏感的正則表達式(
var str = "Hello, World!"; str = str.replace("World", ""); // Removes "World"
問:如何刪除第一個字符? >a:
>使用>方法:>
i
>
var str = "Hello, World!"; str = str.replace(/world/i, ""); // Removes "World" regardless of case
a:>使用>方法:
>
問:如何在特定位置上刪除字符?
substring()
>
var str = "Hello, World!"; str = str.substring(1); // Removes the "H"
兩次:>
問:如何刪除所有空間?
>a:slice()
使用與所有空格字符匹配的正則表達式:
var str = "Hello, World!"; str = str.slice(0, -1); // Removes the "!"
問:如何刪除所有非alphanumeric字符? >
a:使用匹配非alphanumeric字符的正則表達式:
slice()
var str = "Hello, World!"; str = str.slice(0, 5) + str.slice(6); // Removes the character at position 6 (index 5)
a:>使用將匹配固定到字符串末端()末端的正則表達式:
以上是jQuery從字符串中刪除字符串的詳細內容。更多資訊請關注PHP中文網其他相關文章!