MyString = "big BANANA: 5, pineapple(7), small Apples_juice (1,5%)_, oranges* juice 20 %, , other fruit : no number "
我希望获得MyString
中每个元素的数量。
十进制分隔符可以是逗号或点。
我试过的代码:
function getValue(string, word) {
var index = string.toLowerCase().indexOf(word.toLowerCase()),
part = string.slice(index + word.length, string.indexOf(',', index));
return index === -1 ? 'no ' + word + ' found!' // or throw an exception
: part.replace(/[^0-9$.,]/g, '');
}
答案 0 :(得分:0)
我建议您重写代码以将值放在对象中:
var myObj = {
bigBanana: 5,
pineapple: 7,
smallApplesJuice: 1.5,
...
}
然后,您可以使用简单的for ... in循环遍历myObj值。
如果这不可行,那么您必须使用RegEx为您想要获取大字符串的每个子字符串创建不同的代码。例如,尝试使用此方法获取Apples_juice的值:
//create a regular expression that matches everything after "Apples_juice":
var re = new RegExp(/((?<=Apples_juice).*$)/);
//extract three characters that follow "Apples_juice (":
var extracted_value = MyString.match(re)[0].substring(2,5);
请注意,extracted_value是一个字符串,您必须将其转换为数字。希望这会有所帮助。
答案 1 :(得分:0)
如果我没有弄错的话,查看你的示例字符串,你想从可以用逗号和空格,
分割的部分中获取数字。
如果是这种情况,那么这可能是一个选项:
\d+(?:[.,]\d+)?
之类的模式进行匹配例如:
var MyString = "big BANANA: 5, pineapple(7), small Apples_juice (1,5%)_, oranges* juice 20 %, , other fruit : no number ";
function getValue(string, word) {
var items = string.toLowerCase().split(', ');
word = word.toLowerCase();
var pattern = /\d+(?:[.,]\d+)?/g;
var result = 'no ' + word + ' found!';
for (var i = 0; i < items.length; i++) {
var item = items[i];
if (item.indexOf(word) !== -1) {
var match = item.match(pattern);
if (match && typeof match[0] !== 'undefined') {
result = match[0];
}
}
}
return result;
}
console.log(getValue(MyString, "big BANANA"));
console.log(getValue(MyString, "pineapple"));
console.log(getValue(MyString, "small Apples_juice"));
console.log(getValue(MyString, "oranges* juice"));
console.log(getValue(MyString, "other fruit"));
console.log(getValue(MyString, "ApPle"));