user
In JavaScript, how to check whether a string contains a carriage return?
alphonsio

In JavaScript, ou can check if a string contains a carriage return using the includes method:

if (str.includes('\r')) {
   // Do something
}

In JavaScript, you can check whether a string contains a carriage return (CR) character using the includes method or a regular expression. The carriage return character is represented by \r.

Using includes Method

The includes method determines whether a string contains a specified substring. Here's how you can use it to check for a carriage return:

let str = "Hello\rWorld";

if (str.includes('\r')) {
    console.log("The string contains a carriage return.");
} else {
    console.log("The string does not contain a carriage return.");
}

Using Regular Expression

You can also use a regular expression to check for a carriage return:

let str = "Hello\rWorld";

if (/\r/.test(str)) {
    console.log("The string contains a carriage return.");
} else {
    console.log("The string does not contain a carriage return.");
}

Test carriage return and line feed

If you need to check for carriage return (\r) or line feed (\n) , use the following regular expression:

var str = "Hello\nWorld";
if (/\r|\n/.exec(str)) {
    console.log("The string contains a carriage return or a line break.");
} else {
    console.log("The string does not contain a carriage return or a line break.");
}

Explanation

  • includes('\r'): This method checks if the substring \r (carriage return) is present in the string.
  • /\r/.test(str): This uses a regular expression to test if the carriage return character is present in the string.

Both methods will effectively determine whether a string contains a carriage return in JavaScript. Choose the one that best fits your coding style or needs.