2016-07-25 62 views
0

提取的话我有一个字符串如下图所示与某个字符开始从一个字符串在Javascript

var str = "This product price is £15.00 and old price is £19.00"; 

我需要得到以“£”开头的词; 的结果应该是“£15.00”,“19.00£” 我怎么做的Javascript?

+1

使用'.match()'方法使用正则表达式。 – nnnnnn

+0

我试过这个@nicael,str.indexOf('£')。我知道它会返回字符串的索引。我也得到.match()的解决方案。 – Sathya

回答

6

使用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));

0

有一个可能性:

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]); 
    } 
} 
1

使用.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);

0

使用正则表达式的表达式,存储在一个阵列中的每个识别的词(在这种情况下的价格),然后在需要时抓住它可以按如下方式做到这一点

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. 
} 
0

您可以使用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"] 

简短说明:

此正则表达式匹配,其与£标志开始的所有单词,其次是最小的一个,以n个数字..

£[0-9]+ 

..并可选有两位十进制数字。

(.[0-9]{1,2})? 

g修饰符会导致全局搜索。

相关问题