[英]How to remove a word that starts with a certain character from a string in Javascript
[英]Extract words that starts with a certain character from a string in Javascript
我有一個字符串,如下所示
var str = "This product price is £15.00 and old price is £19.00";
我需要得到以“£”開頭的單詞; 結果應該是“£15.00”“£19.00”如何使用Javascript?
使用String#match
方法
var str = "This product price is £15.00 and old price is £19.00"; // if `£` follows non-digit also then use console.log(str.match(/£\\S+/g)); // if `£` follows only number with fraction console.log(str.match(/£(\\d+(\\.\\d+)?)/g));
使用.split()
將字符串轉換為數組,然后使用.filter
和您要查找的內容創建一個新數組。
var str = "This product price is £15.00 and old price is £19.00"; var r = str.split(" ").filter(function(n) { if(/£/.test(n)) return n; }); console.log(r);
有可能:
var myChar = '£';
var str = "This product price is £15.00 and old price is £19.00";
var myArray = str.split(' ');
for(var i = 0; i < myArray.length; i++) {
if (myArray[i].charAt(0) == myChar) {
console.log(myArray[i]);
}
}
您可以使用regex表達式進行以下操作,將每個識別的單詞(在這種情況下為價格)存儲在數組中,然后在需要時進行抓取
var re = /(?:^|[ ])£([a-zA-Z]+)/gm;
var str = 'This product price is £15.00 and old price is £19.00';
var identifiedWords;
while ((identifiedWords = re.exec(str)) != null) {
if (identifiedWords.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the "identifiedWords" variable.
// eg identifiedWords[0] etc.
}
您可以使用RegEx實現此目的:
let str = "This product price is £15.00 and old price is £19.00";
let res = str.match(/£[0-9]+(.[0-9]{1,2})?/g);
結果將是:
["£15.00", "£19.00"]
簡短說明:
此RegEx匹配所有以£
符號開頭,后跟至少一位到n位數字的單詞。
£[0-9]+
..和optional有兩個十進制數字。
(.[0-9]{1,2})?
g
修飾符引起全局搜索。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.