Skip to main content

Command Palette

Search for a command to run...

javascript.info Notes - Strings

Published
2 min readView as Markdown

Three ways to declare strings in JS

let single = 'single-quoted';
let double = "double-quoted";
let backticks = `backticks`;

Accessing characters

let str = `Hello`;

// the first character
console.log( str[0] ); // H
console.log( str.at(0) ); // H

// the last character
console.log( str[-2] ); //Error, negative not allowed
console.log( str[str.length - 1] ); // hack, works
console.log( str.at(-1) ); // the right way to do it

Searching for a substring


let str = 'Widget with id';

console.log( str.indexOf('Widget') ); // 0, because 'Widget' is found at the beginning
console.log( str.indexOf('widget') ); // -1, not found, the search is case-sensitive
console.log( str.indexOf("id") ); // 1, "id" is found at the position 1 (..idget with id)

//The optional second parameter allows us to start searching from a given position.
console.log( str.indexOf('id', 2) ) // 12

//str.lastIndexOf(substr, position)
console.log( str.lastIndexOf(str, 5)) //guess

console.log( str.includes("Widget") ); // true

console.log( str.includes("Bye") ); // false
console.log( str.startsWith("Wid") ); // true, str starts with "Wid"
console.log( str.startsWith("Hello") ); // false
console.log( str.endsWith("id") ); // true
console.log( str.endsWith("get") ); // false

Getting a substring

There are 3 methods in JavaScript to get a substring: substring, substr and slice.

just google these when needed, it is really difficult to remember the details. Remember slice if you have to because it seems to be the most flexible.