gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:39:49 25 4
gpt4 key购买 nike

我希望根据节点中的评论将某些单词转换为图标。

我需要像这样转换一个字符串:

This is my fav item :9044: and :456:

进入一个 js 数组,如:

[ 9044, 456 ]

我在网上尝试了各种 Regex 方法,但都没有产生正确的输出。

以前失败的尝试:

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

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

最佳答案

您可以使用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);

关于javascript - JS - 收集字符之间的所有字母(:),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50402190/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com