我想在每隔三个空格分割字符串。例如:
var str = 'Lorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor incididunt';
//result will be:
var result = ["Lorem ipsum dolor ", "sit amet consectetur ", "adipiscing elit sed ", "do eiusmod tempor ", "incididunt"];
请帮帮我。谢谢
答案 0 :(得分:4)
使用正则表达式分割字符串。
var str = 'Lorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor incididunt';
var splited = str.match(/\b[\w']+(?:[^\w\n]+[\w']+){0,2}\b/g);
console.log(splited);

正则表达式说明:
1. \b assert position at a word boundary (^\w|\w$|\W\w|\w\W)
2. Match a single character present in the list below [\w']+
\w matches any word character (equal to [a-zA-Z0-9_])
3. {0,2} Quantifier — Matches between 0 and 2 times
4. Match a single character not present in the list below [^\w\n]
5. \w matches any word character (equal to [a-zA-Z0-9_])
6. \n matches a line-feed (newline) character (ASCII 10)
7. Match a single character present in the list below [\w']
8. \w matches any word character (equal to [a-zA-Z0-9_])
9. ' matches the character ' literally (case sensitive)
10. \b assert position at a word boundary (^\w|\w$|\W\w|\w\W)
11. g modifier: global. All matches (don't return after first match)
答案 1 :(得分:2)
var str = 'Lorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor incididunt';
var splitString = str.match(/(.*?\s){3}/g);
console.log(splitString);
答案 2 :(得分:0)
点击https://regex101.com/r/npQt7X/1
或
const regex = /\b[\w']+(?:[^\w\n]+[\w']+){0,2}\b/g;
const str = `Lorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor incididunt`;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
答案 3 :(得分:0)
正则表达式很好,但难以解释并且难以阅读。
因此,只有在没有其他解决方案时才使用正则表达式。
反对这些正则表达式的论据是参数的硬编码。
var str = 'Lorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor incididunt';
var splitMyString = (str, splitLength) => {
var a = str.split(' '), b = [];
while(a.length) b.push(a.splice(0,splitLength).join(' '));
return b;
}
console.log(splitMyString(str,3));