我想做jQuery整数和字符串解析。用户只需在textarea中输入字符串。
1。)首先从句子中获取不属于字符串的整数。
input integer output text output
1 7-up 1 7-up
3 coke 3 coke
8 popcorn 8 popcorn
6cups 5 5 6cups
通过此设置,我已经可以解析用户输入的每行输入的整数。 那我怎么能实现目标呢?
答案 0 :(得分:0)
考虑到您发布的信息量,很难提供帮助,但如果您有这样的HTML
<!doctype html>
<html>
<head>
</head>
<body>
<textarea>1 7-up</textarea>
<textarea>3 coke</textarea>
<textarea>8 popcorn</textarea>
<textarea>6cups 5</textarea>
</body>
</html>
这应该是你的JavaScript:
var parsed = $('textarea').map(function() {
return this.value;
}).toArray().reduce(function(result, input, input_index) {
if(result === false) return;
var value = input.match(/\b(\d+)\b/);
if(value === null) {
alert('Unable to find the value/digit from input: ' + (input_index + 1));
return false;
}
result.push({
text: input.replace(value[0], '').replace(/^\s*|\s*$/g, ''),
number: value[0]
});
return result;
}, []);
console.log(parsed);
/*
[
{
"text": "7-up",
"number": "1"
},
{
"text": "coke",
"number": "3"
},
{
"text": "popcorn",
"number": "8"
},
{
"text": "6cups",
"number": "5"
}
]
*/