【问题标题】:Replace double new line character with only one?只用一个替换双换行符?
【发布时间】:2019-02-19 16:35:57
【问题描述】:

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

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, '')

【问题讨论】:

  • 删除[...]
  • 抱歉,这个 [...] 是什么意思?编辑:我明白你的意思是正则表达式中的括号,我正在尝试!非常感谢!

标签: javascript replace newline


【解决方案1】:
string = string.replace(/\n{2}/g, '\n');

console.log(string);

这将按照你的解释......但我相信你需要这个......

string = string.replace(/\n+/g, '\n');

console.log(string);

【讨论】:

    【解决方案2】:

    [\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

    【讨论】:

      猜你喜欢
      • 2011-05-02
      • 1970-01-01
      • 2016-12-30
      • 2021-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-16
      相关资源
      最近更新 更多