【问题标题】:Javascript Line break detection and line break preservationJavascript换行检测和换行保存
【发布时间】:2020-09-24 19:28:48
【问题描述】:

我写了一个函数来将每个句子开头的每个字母大写。我想将最初具有换行符的文本从文本区域输出到文本区域。输出文本应保留这些换行符。但是我的代码忽略了所有的换行符。你能帮我解决这个问题吗?我的代码:

btnPara.addEventListener("click", (e) => {
  e.preventDefault();

  function paragraphMode(str) {
    var splitPara = str
      .split(/\r?\n/)
      .join(" ")
      .split(". ")

      .map(
        (sentence) => sentence.charAt(0).toUpperCase() + sentence.substring(1)
      );

    return splitPara.join(". ");
  }
  outputText.value = paragraphMode(inputText.value);
});

【问题讨论】:

  • .split(/\r?\n/) 将删除那些换行符

标签: javascript line-breaks capitalize


【解决方案1】:

您不需要处理换行符,您只需要在. 之后查找所有出现的第一个字符。例如,您可以使用/(^|\.)\s*(\w)/g

const process = s => s.replace(/(^|\.)\s*(\w)/g,w=>w.toUpperCase())

console.log(process("abc.    def .  g   h . ijk lm. \n O \n pq\nR\ns"))
console.log(process("some text is\nwritten here.  it doens't\nproperly capitalize sentences.\ncan we fix it?")) // example sentence suggested by @ Scott Sauyet

顺便说一句,为了与原始代码相同的效果(匹配句点后只有一个空格/换行符),您只需将 \s* 更改为 \r?[\n ]

const input = "abc.    def .  g   h . ijk lm. \n O \n pq\nR"
const result = input.replace(/(^|\.)(\r?\n| )(\w)/g,w=>w.toUpperCase())
console.log(result)

【讨论】:

  • 比我的简单多了。我很快就会删除我的。但在那之前,你可能想刷一下我的测试字符串。比上面的更容易理解。
  • 建议测试用例:"some text is\nwritten here. it doens't\nproperly capitalize sentences.\ncan we fix it?"
  • 或者如果你想扩展处理?!,那么可能是这样的:"some initial text is written here. it is wonderful\ntext! but it doens't\nproperly capitalize sentences.\ncan we fix it? let's see."
猜你喜欢
  • 2019-04-16
  • 2012-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-15
相关资源
最近更新 更多