![](/img/trans.png)
[英]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.