【发布时间】:2020-10-08 03:24:21
【问题描述】:
如何将一个字符串分块成 3 个单词(或更少)的短语,并在末尾加上括号?
下面是一个示例字符串
This is a sample sentence containing some words with some other meanings.
以下是预期的结果
[This is a sample] [sentence containing some] [words with some] [other meanings.]
我添加了我的
这是我试过的
this.mod = this.data.replace(/([.?!])\s*(?=[A-Z])/g, "$1|").split("|");
this.mod.map((sentence) => {
sentence.split(' ').reduce((acc, cur, idx, arr) => {
acc + cur
} ,'')
})
这也是我尝试过的,但它不起作用。
const res = this.mod.map((sentence) => {
return sentence.split(" ").reduce((acc, cur, idx, arr) => {
acc + (idx % 3 === 0) ? `][${cur}]` : cur;
}, "[");
});
还有其他方法吗?
【问题讨论】:
-
你如何确定一个短语?你试过什么?
-
谁的头脑正常,两次点赞这篇帖子?
-
嗨。我不确定如何确定短语。
-
有没有办法确定词组?
-
使用正则表达式:
'This is a sample sentence containing some words with some other meanings.'.replace(/(\w+ \w+(?: \w+)?)/g,'[$1]')
标签: javascript