Strings created with single or double quotes works the same.
There is no difference between the two.
1. Creating Strings:
- You can create strings using string literals or the
String()
constructor:
const str1 = 'Hello, world!';
const str2 = "JavaScript is awesome!";
const str3 = new String
('This is a string object.');
2. Accessing Characters:
- You can access individual characters of a string using square brackets
[]
and the character’s index, which starts from 0
console.log(str1[0]); // Outputs: 'H'
console.log(str2.charAt(4)); // Outputs: 'S'
3. String Properties and Methods:
length
: Property that returns the length of the string.concat()
: Method that concatenates two or more strings and returns a new string.toUpperCase()
: Method that converts the string to uppercase.toLowerCase()
: Method that converts the string to lowercase.indexOf()
: Method that returns the index within the calling String object of the first occurrence of the specified value.slice()
: Method that extracts a section of a string and returns it as a new string.substring()
: Method that returns the part of the string between the start and end indexes.replace()
: Method that replaces a specified value with another value in a string.split()
: Method that splits a string into an array of substrings based on a specified separator.
Example Usage:
const sentence = 'JavaScript is fun!';
console.log(sentence.length); // Outputs: 18
console.log(sentence.concat(' Especially
when you learn it.')); // Outputs: JavaScript is fun!
Especially when you learn it.
console.log(sentence.toUpperCase()); // Outputs:
JAVASCRIPT IS FUN!
console.log(sentence.indexOf('fun')); // Outputs: 11
console.log(sentence.slice(0, 10)); // Outputs:
JavaScript
console.log(sentence.replace('fun', 'exciting'));
// Outputs: JavaScript is exciting!
console.log(sentence.split(' ')); // Outputs:
['JavaScript', 'is', 'fun!']
4. Template Literals:
Template literals, introduced in ECMAScript 6 (ES6), provide an easy way to create strings with placeholders for variables and expressions. They are enclosed in backticks (“) and can span multiple lines:
const name = 'Alice';
const age = 30;
const message = `Hello, my name is ${name} and
I'm ${age} years old.`;
console.log(message); // Outputs: Hello,
my name is Alice and I'm 30 years old.
Template Strings
- Templates were introduced with ES6 (JavaScript 2016).
Templates are strings enclosed in backticks (`This is a template string`).
Templates allow multiline strings:
let text =
`The quick
brown fox
jumps over
the lazy dog`;