Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
With JavaScript RegExp search a carriage return character.
To find carriage return characters with JavaScript Regular Expression, use the \r metacharacter. This pattern matches the carriage return character (ASCII code 13) in strings.
Syntax
/\r/
Example: Finding Carriage Return Position
The following example shows how to search for a carriage return character and return its position in the string:
<html>
<head>
<title>JavaScript Regular Expression</title>
</head>
<body>
<script>
var myStr = "100% \r Responsive!";
var reg = /\r/;
var match = myStr.search(reg);
document.write("Position of carriage return: " + match);
</script>
</body>
</html>
Position of carriage return: 4
Testing for Carriage Return
You can also use the test() method to check if a carriage return exists:
<html>
<head>
<title>Testing Carriage Return</title>
</head>
<body>
<script>
var str1 = "Hello\rWorld";
var str2 = "Hello World";
var regex = /\r/;
document.write("String 1 has carriage return: " + regex.test(str1) + "<br>");
document.write("String 2 has carriage return: " + regex.test(str2));
</script>
</body>
</html>
String 1 has carriage return: true String 2 has carriage return: false
Common Use Cases
Carriage return detection is useful for:
- Processing text files from Windows systems
- Cleaning up user input from text areas
- Converting line endings between different systems
Conclusion
Use /\r/ regex pattern to detect carriage return characters in JavaScript strings. The search() method returns the position, while test() returns a boolean result.
Advertisements
