Open In App

How to get raw content from a string including carriage return ?

Last Updated : 05 Jun, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

The raw content of a string includes the carriage returns, i.e. it contains the new line escape sequence.

Note: The line feed, represented by “\n” and a carriage return “\r” are very different. A line feed means moving the cursor one line forward. A carriage return means moving the cursor to the beginning of the line. Windows editors still use the combination of both as ‘\r\n’ in text files. Unix uses mostly only the ‘\n’. For simplicity, we will consider line breaks as ‘\n’, i.e., move to the next line.

The conversion of the string to its raw form can be done using two methods that are discussed below:

Method 1: Using JSON.stringify() method: The JSON.stringify() method is used to convert a JavaScript object or value to a JSON string. The below example represents how the raw content can be obtained using this method:

javascript




<script>
// Define the original string
const str = 'Geeks\nFor\nGeeks';
  
console.log('Original String:');
console.log(str);
console.log('');
  
// Find the raw content
// using JSON.stringify()
console.log('Raw content:');
console.log(JSON.stringify(str));
</script>


Output:

Original String:
Geeks
For
Geeks

Raw Content:
"Geeks\nFor\nGeeks"

Method 2: Using string.replace() method: The string.replace() method is used to replace a part of the given string with some another string or a regular expression. The original string will remain unchanged. Regular expressions are used to replace the needed parts of the string. The ‘g’ parameter in the regular expression make sure that all ‘\n’ characters are converted to their raw forms.

 The below example represents how the raw content can be obtained using this method:

javascript




<script>
// Define the original string
const str = 'Geeks\nFor\nGeeks';
  
console.log('Original String:');
console.log(str);
console.log('');
  
// Find the raw content
// using JSON.stringify()
console.log('Raw content:');
console.log(str.replace(/\n/g, `\\n`));
</script>


Output:

Original String:
Geeks
For
Geeks

Raw Content:
"Geeks\nFor\nGeeks"


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads