我有一根绳子。
const str = "This is a test.\n\nAnother Sentence.\nHello!";
我想要结果
// ['This', 'is', 'a', 'test.', '\n', '\n', 'Another', 'Sentence.', '\n', 'Hello!']
我在做
const arr = str.match(/\w+/g);
// ["This", "is", "a", "test", "Another", "Sentence", "Hello"]
我应该怎么做才能在结果中包含所有特殊字符,例如 (.) 和 (!) 等以及“\n”?能否请你帮忙?
最佳答案
您可以使用
/\S+|\n/g
请参阅regex demo 。它匹配 1 个以上非空白字符或换行符,次数与输入字符串中此类 block 的次数相同(由于 g
修饰符)。
JS 演示:
var str = "This is a test.\n\nAnother Sentence.\nHello!";
console.log(str.match(/\S+|\n/g));
关于javascript - 正则表达式按字面意思匹配单词和\n,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57599302/