How to remove all line breaks from a string

前端 未结 16 1576
轮回少年
轮回少年 2020-11-22 11:36

I have a text in a textarea and I read it out using the .value attribute.

Now I would like to remove all linebreaks (the character that is produced when you press

16条回答
  •  广开言路
    2020-11-22 12:12

    The answer provided by PointedEars is everything most of us need. But by following Mathias Bynens's answer, I went on a Wikipedia trip and found this: https://en.wikipedia.org/wiki/Newline.

    The following is a drop-in function that implements everything the above Wiki page considers "new line" at the time of this answer.

    If something doesn't fit your case, just remove it. Also, if you're looking for performance this might not be it, but for a quick tool that does the job in any case, this should be useful.

    // 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`)
    });
    

提交回复
热议问题