Strings - Javascript

Concatenate two strings

let firstName = "John";
let lastName = "Snow";
console.log(firstName + lastName);

Output: JohnSnow

 

Escaping quote

// Escaping string
let sentence = 'That\'s interesting, it\'s gonna be awesome';
console.log(sentence);

Output: That's interesting, it's gonna be awesome

Length of a string

console.log('NewYork'.length);

Output: 7

concat() function

console.log('NewYork'.concat(' Rocks'));

Output: NewYork Rocks

Change case

console.log('NewYork'.toUpperCase());
console.log('NewYork'.toLowerCase());

Output:

NEWYORK

newyork

Index of a character in a string, character at an index

let val1 = 'California';
console.log(val1.indexOf('C'));
console.log(val1.indexOf('i'));
console.log(val1.lastIndexOf('i'));
console.log(val1.charAt(3));

Output:

0

3

8

i

In javascript , remember index start with zero

Also notice the behaviour of lastIndexOf() function, as name suggest it gives the last index value of the required character.

charAt() function output the character given at the required index in string.

substring, slice()

let val1 = 'California';
console.log(val1.substring(2,5));
console.log(val1.slice(2,5));
console.log(val1.slice(-4));

Output:

split

let val1 = 'This is a full sentence.';
console.log(val1.split());

Output:

let val1 = 'This is a full sentence.';
console.log(val1.split(' '));

Output:

 

replace, includes

let val1 = 'This is a full sentence.';
console.log(val1.replace('This is', 'That was'));

Output: That was a full sentence.

 

let val1 = 'This is a full sentence.';
console.log(val1.includes('full'));

Output: true

 

None