JS - 收集一个字符之间的所有字母(:)

时间:2018-05-18 00:29:30

标签: javascript regex

我希望根据节点中的注释内容将某些单词转换为图标。

我需要转换一个字符串,如:

  

这是我最喜欢的项目:9044:和:456:

进入js数组,如:

[ 9044, 456 ]

我在网上尝试了各种正则表达式,但没有一种方法能够产生正确的输出。

以前失败的尝试:

------------------

var comment = 'This is my fav item :9044: and :456:';
comment.substring(comment.lastIndexOf(":")+1,comment.lastIndexOf(":"));

// ':'

enter image description here

------------------

var comment = 'This is my fav item :9044: and :456:';
comment.match(":(.*):");

// [ ':9044: and :456:', '9044: and :456' ]

enter image description here

------------------

var comment = 'This is my fav item :9044: and :456:';
comment.match(/:([^:]+):/);

// [ ':9044:', '9044' ]

enter image description here

1 个答案:

答案 0 :(得分:6)

您可以使用regex.exec

var input = 'This is my fav item :9044: and :456: and another match :abc:';

let regex = /:(\w+):/g;
let results = [];
let number;

while(number = regex.exec(input)) {
  results.push(number[1]);
}
 
console.log(results);

regex = /:\w+:/g;
results = input.match(regex).map(num => num.replace(/:/g, ''));
 
console.log(results);

// And it you want to cast numbers
results = input.match(regex).map(num => {
   num = num.replace(/:/g, '');
   return Number.isNaN(+num) ? num : +num;
});
 
console.log(results);