YouTip LogoYouTip

Js Strings

# JavaScript Strings * * * JavaScript strings are used for storing and manipulating text. * * * ## JavaScript Strings A string can be any text inside quotes. You can use single or double quotes: ## Example var carname = "Volvo XC60"; var carname = 'Volvo XC60'; You can access the characters in a string by index position: ## Example var character = carname; String indexes start at 0, meaning the first character has index , the second , and so on. ## Example const name =""; let letter = name; document.getElementById("demo").innerHTML= letter; [Try it Β»](#) You can use quotes inside a string, as long as they don't match the quotes around the string: ## Example var answer = "It's alright"; var answer = "He is called 'Johnny'"; var answer = 'He is called "Johnny"'; You can also add escape characters to use quotes inside a string: ## Example var x = 'It's alright'; var y = "He is called "Johnny""; [Try it Β»](#) * * * ## String Length The built-in property **length** can be used to find the length of a string: ## Example var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; var sln = txt.length; [Try it Β»](#) * * * ## Special Characters In JavaScript, strings are written with double or single quotes. Because of this, the following example cannot be parsed by JavaScript: "We are the so-called "Vikings" from the north." The string "We are the so-called " is truncated. How to solve this problem? Use an escape character () to escape the double quotes in the "Vikings" string, like this: "We are the so-called "Vikings" from the north." The backslash () is an **escape character**. Escape characters turn special characters into string characters: The escape character () can be used to escape other special characters like apostrophes, newlines, quotes, etc. The following table lists the special characters that can be escaped in a string: | Code | Output | | --- | --- | | ' | Single quote | | " | Double quote | | | Backslash | | n | New line | | r | Carriage return | | t | Tab | | b | Backspace | | f | Form feed | * * * ## Strings are Objects Normally, JavaScript strings are primitive values, created from literals: **var firstName = "John"** But strings can also be defined as objects with the **new** keyword: **var firstName = new String("John")** ## Example var x = "John"; var y = new String("John"); typeof x // returns String typeof y // returns Object [Try it Β»](#) | ![Image 2: Note](#) | Do not create String objects. It slows down execution speed and can cause other side effects: | | --- | ## Example var x = "John"; var y = new String("John"); (x === y) // returns false because x is a string, y is an object [Try it Β»](#)
← Met Document QueryselectorJs Events β†’