java去掉字符串中换行_如何从字符串中删除所有换行符?

PointedEars提供的答案是我们大多数人所需要的 . 但是按照Mathias Bynens的回答,我进行了一次维基百科之旅,发现了这个:https://en.wikipedia.org/wiki/Newline .

以下是一个插件函数,它实现了上述Wiki页面在此答案时认为“新行”的所有内容 .

如果某些内容不适合您的情况,请将其删除 . 此外,如果您正在寻找性能,这可能不是它,但对于在任何情况下完成工作的快速工具,这应该是有用的 .

// replaces all "new line" characters contained in `someString` with the given `replacementString`

const replaceNewLineChars = ((someString, replacementString = ``) => { // defaults to just removing

const LF = `\u{000a}`; // Line Feed (\n)

const VT = `\u{000b}`; // Vertical Tab

const FF = `\u{000c}`; // Form Feed

const CR = `\u{000d}`; // Carriage Return (\r)

const CRLF = `${CR}${LF}`; // (\r\n)

const NEL = `\u{0085}`; // Next Line

const LS = `\u{2028}`; // Line Separator

const PS = `\u{2029}`; // Paragraph Separator

const lineTerminators = [LF, VT, FF, CR, CRLF, NEL, LS, PS]; // all Unicode `lineTerminators`

let finalString = someString.normalize(`NFD`); // better safe than sorry? Or is it?

for (let lineTerminator of lineTerminators) {

if (finalString.includes(lineTerminator)) { // check if the string contains the current `lineTerminator`

let regex = new RegExp(lineTerminator.normalize(`NFD`), `gu`); // create the `regex` for the current `lineTerminator`

finalString = finalString.replace(regex, replacementString); // perform the replacement

};

};

return finalString.normalize(`NFC`); // return the `finalString` (without any Unicode `lineTerminators`)

});

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值