js识别字符串中换行符
warning:
这篇文章距离上次修改已过429天,其中的内容可能已经有所变动。
在JavaScript中,可以使用正则表达式来识别字符串中的换行符。换行符可以是\n、\r或者是\r\n组合,具体取决于操作系统。以下是一个示例函数,它接收一个字符串并返回一个布尔值,表示字符串中是否包含换行符:
function containsNewline(str) {
return /\n|\r\n?/.test(str);
}
// 示例使用
const stringWithNewline = "Hello,\nWorld!";
const stringWithoutNewline = "Hello, World!";
console.log(containsNewline(stringWithNewline)); // 输出: true
console.log(containsNewline(stringWithoutNewline)); // 输出: false这个正则表达式/\n|\r\n?/会匹配\n,或者匹配\r后可选的\n。如果字符串中有至少一个这样的序列,test方法将返回true,否则返回false。
评论已关闭