从文本中提取一定数量

时间:2018-08-12 05:58:42

标签: javascript jquery

我想问一下如何从文本中提取某些数字?例如,我有此文本行。

Last edited by SarkZKalie on Wed 8 Aug - 2:17; edited 1 time in total
Last edited by SarkZKalie on Wed 8 Aug - 2:17; edited 12 times in total

如您所见,该文本行本身具有一种日期格式,但是请不要在意,我只希望您将其后的焦点放在“ 1次”或“ 11次”上。

脚本应该返回一个类似于.getElementById(“ lastedit”)的结果,然后在按钮html标记中插入我们得到的数字。

<button id="lastedit" title="Edited NUMBER time(s) in total">NUMBER</button>

对不起,我的英语不好。

2 个答案:

答案 0 :(得分:1)

示例1-一行

$("#lastedit").text(
  parseInt("Last edited by SarkZKalie on Wed 8 Aug - 2:17; edited 12 times in total"
    .split(/; edited /)[1]
  )
)  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="lastedit" title="Edited NUMBER time(s) in total">NUMBER</button>

示例2,将编辑次数加起来

const list = `Last edited by SarkZKalie on Wed 8 Aug - 2:17; edited 1 time in total
Last edited by SarkZKalie on Wed 8 Aug - 2:17; edited 12 times in total`

$("#lastedit").text(
  list.split(/; edited /) // split on the word before the number
    .slice(1)             // get rid of the first line
    .reduce(( x, v ) => x + parseInt(v),0) // sum the array of numbers
)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="lastedit" title="Edited NUMBER time(s) in total">NUMBER</button>

答案 1 :(得分:0)

let str = 'Last edited by SarkZKalie on Wed 8 Aug - 2:17; edited 12 times in total'
console.log(get(str))

var str2 = 'Last edited by SarkZKalie on Wed 8 Aug - 2:17; edited 1 time in total'
console.log(get(str2))

function get(str) {
  const match = str.match(/\d+/g)
  return match[match.length - 1]
}