Jquery 解析不属于字符串的句子/行中的整数

Jquery parse integer in a sentence/line that is not part of the string

本文关键字:整数 句子 Jquery 不属于 字符串      更新时间:2023-09-26

我想做jQuery整数和字符串解析。用户只需在文本区域中输入字符串。

1.( 首先从不属于字符串的句子中获取整数。

input           integer output   text output     
1 7-up            1                 7-up
3 coke            3                 coke
8 popcorn         8                 popcorn
6cups 5           5                 6cups

通过此设置,我已经可以解析用户输入的每行整数。那么我怎样才能实现目标呢?

考虑到您发布的信息量,很难提供帮助,但是如果您有这样的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"
  }
]
*/