JavaScript escape sequences

 JavaScript escape sequences



JavaScript escape sequences help you to format stuff on your website. One typical example is to print something on a new line.

We already know how to escape single and double quotes. If you don't know how, read this first.

Quotes aren't the only things that can be escaped. You use escape sequences for the following things.

Let's look at an example.
let info = "You can\'t visit me during lockdown. Be safe.";

To put the words Be Safe on a new line you would use \n which is used to print something on a new line. Line feed means moving one line forward.
let info = "You can\'t visit me during lockdown. \n Be safe.";

To add a tab to indent something you would use \t escape character. This would add four spaces before the word Be safe.
let info = "You can\'t visit me during lockdown. \t Be safe.";

You can use carriage return to move the cursor to the beginning of the line. Use \r.
let info = "You can\'t visit me during lockdown. \t Be safe. \r";

You have \f which returns the position where the form feed character was found. Let's see where the word safe is and get the count of characters before it. It returns -1 when the string is not found. This returns 40 in our case.
let info = "You can\'t visit me during lockdown. Be \fsafe.";
info.search("\f"); // This is the right way of doing it. Returns 39.
info.search("safe"); 

In the video tutorial, I've actually covered the .safe method, please ignore it for now. We will practice them on a separate lesson. 

You can also escape and print a backslash when needed using \\.

We also have word boundary which is \b that we won't cover in basics. You can look here you are interested.



Post a Comment

0 Comments

React