Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Length of special characters in javascript

Why is the length of "\n\n\n" 3? Is it because \n is a special character in JS?

var temp = "\n\n\n";
var length = temp.length; //Expected:6 Actual:3
like image 582
halapgos1 Avatar asked Jan 31 '26 04:01

halapgos1


1 Answers

Because \n is an escape sequence.

The \ (backslash) is an escape character that means that the immediately following character should be interpreted differently than it usually is. This is used in several programming languages (not just JavaScript) to represent a single character that can't be typed or would cause confusion in a string literal (for example, double or single quotes). In this case, the sequence \n represents a single "new line" character, and you have three of them, so the length is three.

like image 126
Herohtar Avatar answered Feb 02 '26 18:02

Herohtar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!