Strings
In JavaScript, strings are a primitive data type used to represent textual data. They are sequences of characters,
String methods and properties
JavaScript provides various built-in methods and properties for working with strings, including:
length: Returns the number of characters in the string.indexOf()andincludes(): For searching within strings.slice(),substring(), andsubstr(): For extracting parts of a string.toUpperCase()andtoLowerCase(): For case conversion.trim(): For removing whitespace from ends.split(): For splitting a string into an array.replace(): For replacing parts of a string.
Creating strings
Strings can be created using single quotes:
'Hello'
Strings can also be created using double quotes:
"World"
When combining JavaScript and HTML, it is a good idea to use one style of quotes for JavaScript and the other style for HTML:
<button onclick="alert('Thank you')">Click Me</button>
But using backticks gives you enhanced features like multiline strings and embedded expressions using $. The final value of a string literal in backticks is computed by evaluating included expressions, converting values to strings and combining with the literal characters:
let name = "Bob";
let greeting = `Hello ${ name }`;
Immutability
Once a string is created, its content cannot be directly modified. String methods that appear to modify a string, such as toUpperCase(), slice() or concat(), actually return a new string with the desired changes.
Indexing
Characters within a string can be accessed by their index, starting from 0 for the first character. To access individual characters:
myString[0]
myString[myString.length-1]
No Character Type:
Unlike some other languages, JavaScript does not have a separate char data type; single characters are simply strings of length one.
Escape Sequences
Special characters like quotation marks within a string can be included using escape sequences, such as \" for a double quote or \' for a single quote. Backslashes themselves are escaped with \\.
String concat
Concatenate strings with + operator:
let firstName = "John";
let lastName = "Doe";
let fullName = firstName + " " + lastName; // "John Doe"
However, strings can also be contenated by using backticks:
let greeting = "Hello";
let name = "Alice";
let message = `${greeting} ${name}!`; // "Hello, Alice!"
String compare
Compare strings with === and !== for equality/inequality.
Order strings using: <, <=, <, >=.