首页 > 解决方案 > 只用一个替换双换行符?

问题描述

我怎样才能删除每一个双换行符,只有一个?

var string = "this is a ↵↵↵↵ test there will ↵↵ be more ↵↵↵↵ newline characters"

像这样的东西

var string = "this is a ↵↵ test there will ↵ be more ↵↵ newline characters"

我已经尝试过了,但这会替换所有新行,我想保留单行

string.replace(/[\n\n]/g, '')

标签: javascriptreplacenewline

解决方案


[\n\n]字符类作为Logical OR. [\n\n]这意味着匹配\n\n。你需要的\n\n. 所以只需删除[]字符类。

let str = `this is a 



test there will 

be more 



newline characters`

console.log(str.replace(/\n\n/g, '\n'))
console.log(str.replace(/\n+/g, '\n')) // <--- simply you can do this


推荐阅读