我是相當新的jQuery的/ JS,不知道如何做到以下幾點:使用jQuery查找和替換通配符的文字
Big Sofa - Pink
Big Sofa - Blue
Small Sofa - Red
Small Sofa - Grey
我需要做的是前刪除所有的文本和包括「 - 「所以它只是顯示顏色,需要通配符,所以會得到任何東西,並取而代之。
這可能嗎?
我是相當新的jQuery的/ JS,不知道如何做到以下幾點:使用jQuery查找和替換通配符的文字
Big Sofa - Pink
Big Sofa - Blue
Small Sofa - Red
Small Sofa - Grey
我需要做的是前刪除所有的文本和包括「 - 「所以它只是顯示顏色,需要通配符,所以會得到任何東西,並取而代之。
這可能嗎?
我會建議使用正則表達式。 這裏的例子,當你使用跨度爲每個條目:
$(document).ready(function() {
$("span").each(function() {
var text = $(this).text();
text = text.replace(/(\w+\s)+-\s/g, "");
$(this).text(text);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span>Sofa test - red</span>
<span>Table test - blue</span>
完美的感謝伴侶 – James
試試這個簡單的一個
var a = "Big Sofa - Pink\nBig Sofa - Blue\nSmall Sofa - Red\nSmall Sofa - Grey"
var newA = a.split("\n").map(function(value){ return value.split("-").pop() }).join("\n");
console.log(newA);
最好的辦法是使用正則表達式。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
var text = 'Big Sofa - Pink';
var color = text.replace(/^.+?- (\w+)$/i, '$1'); // Pink
^
字符串的開頭匹配
.
匹配任何字符,包括空格
+
表示前面的匹配器產生倍增後發生1次或更多次
?
表示匹配不是貪婪(匹配最小可能)
-
m atches字面上破折號和空間
(\w+)
匹配任意被1個或多個單詞字符組成的字(字母,數字和下劃線),並捕獲(在這種情況下組1)它的一組中值
$
所述字符串的末尾匹配
i
(末尾),表示該匹配是不區分大小寫的
替換字符串($1
)取代由捕獲組1的內容在我們的情況下,它的顏色相匹配的整個匹配。
這個正則表達式將在多行字符串的工作:
var str = 'Big Sofa - Pink\nBig Sofa - Blue\nSmall Sofa - Red\nSmall Sofa - Grey';
str.replace(/.+\-\s*/g, '').split(/\n/);
你可以做到這一點作爲
var text = "Big Sofa - Pink";
var color = text.substring(text.indexOf("-") + 1)
要做到這一點,最好的方法完全依賴於HTML是如何圍繞這些價值構成的。你能否編輯這個問題來包含更多的HTML。 –