我在textarea中有一个文本,我使用.value属性读取它。
现在我想从我的文本中删除所有的换行符(当你按Enter时产生的字符)现在使用正则表达式替换,但我如何在正则表达式中指示换行符?
如果不可能,还有别的办法吗?
我在textarea中有一个文本,我使用.value属性读取它。
现在我想从我的文本中删除所有的换行符(当你按Enter时产生的字符)现在使用正则表达式替换,但我如何在正则表达式中指示换行符?
如果不可能,还有别的办法吗?
当前回答
在mac上,只需在regexp中使用\n来匹配换行符。代码是字符串。Replace (/\n/g, "), ps:后面的g表示匹配所有,而不仅仅是第一个。
在窗户上,它将是\r\n。
其他回答
PointedEars提供的答案是我们大多数人需要的一切。但根据马赛厄斯·拜恩斯的回答,我在维基百科上找到了这个: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`)
});
如何找到换行符在不同的操作系统编码中是不同的。Windows是\r\n,但Linux只使用\n,而苹果使用\r。
我在JavaScript的换行符中发现了这个:
someText = someText.replace(/(\r\n|\n|\r)/gm, "");
这应该会删除所有的换行符。
使用下面的函数,让您的生活变得简单
最简单的方法是使用正则表达式来检测和替换字符串中的换行符。在这种情况下,我们使用replace函数和要替换的字符串,在我们的情况下是一个空字符串。
function remove_linebreaks( var message ) {
return message.replace( /[\r\n]+/gm, "" );
}
在上面的表达式中,g和m是全局和多行标记
要删除新的行字符,使用以下命令:
yourString.replace(/\r?\n?/g, '')
然后你可以删除字符串的前导和尾随空格:
yourString.trim()
我经常在jsons中的(html)字符串中使用这个正则表达式:
替换(/[\n\r\t\s]+/g, ' ')
字符串来自CMS或i18n php的html编辑器。常见的场景有:
- lorem(.,)\nipsum
- lorem(.,)\n ipsum
- lorem(.,)\n
ipsum
- lorem ipsum
- lorem\n\nipsum
- ... many others with mixed whitespaces (\t\s) and even \r
正则表达式避免了这些丑陋的事情:
lorem\nipsum => loremipsum
lorem,\nipsum => lorem,ipsum
lorem,\n\nipsum => lorem, ipsum
...
当然不是所有的用例,也不是最快的用例,但对于大多数文本区域和网站或web应用程序的文本来说已经足够了。