gpt4 book ai didi

javascript - 将字符串拆分为 n 个单词的数组

转载 作者:数据小太阳 更新时间:2023-10-29 04:56:54 26 4
gpt4 key购买 nike

我想把这个:

"This is a test this is a test"

进入这个:

["This is a", "test this is", "a test"]

我试过这个:

const re = /\b[\w']+(?:[^\w\n]+[\w']+){0,2}\b/
const wordList = sample.split(re)
console.log(wordList)

但是我得到了这个:

[ '',
' ',
' ']

这是为什么?

(规则是每 N 个单词拆分字符串。)

最佳答案

String#split方法将根据匹配的内容拆分字符串,因此它不会在结果数组中包含匹配的字符串。

使用 String#match在正则表达式上使用全局标志 (g) 的方法:

var sample="This is a test this is a test"

const re = /\b[\w']+(?:\s+[\w']+){0,2}/g;
const wordList = sample.match(re);
console.log(wordList);

Regex explanation here.

关于javascript - 将字符串拆分为 n 个单词的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40817167/

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