首页 > 解决方案 > 删除 \n 和 \r 但不删除 \r\n

问题描述

我有一个字符串同时包含\r\n以及\r\n

我们如何删除\rand \n,同时保持\r\n原样?

标签: javascriptregex

解决方案


负前瞻+后视可以做到这一点:

const test="a\nb\rc\r\nd\n\re";
console.log(test.replaceAll(/(\r(?!\n)|((?<!\r)\n))/g,"x"));
//                            ^^^^^^^^              match \r if it has no \n after
//                                     ^^^^^^^^^^^  match \n if it has no \r before

只有\r\n介于cd之间保持完整。


推荐阅读