user
In JS, how to remove carriage return from string?
alphonsio

In JavaScript, to remove carriage return from string, use one of the following Regex

  • str.replace(/[\r]/g, ''); remove only cariage return
  • str.replace(/[\n]/g, ''); remove only new line
  • str.replace(/[\n\r]/g, ''); remove cariage return and new line

Here is a full example :

var str="abc \n def \r ghi";

// Should change str for "abc  def  ghi"
str.replace(/[\n\r]/g, '');

To remove carriage return characters (\r) from a string in JavaScript, you can use the replace() method combined with a regular expression. Here's how you can do it:

Example using replace():

let str = "Hello\rWorld\r!";
let cleanedStr = str.replace(/\r/g, "");
console.log(cleanedStr);

Explanation:

  • \r represents a carriage return.
  • The /\r/g is a regular expression where:
    • \r matches carriage return characters.
    • g is the global flag, meaning it will replace all occurrences of \r in the string, not just the first one.

The result will be "HelloWorld!", with all carriage returns removed.