JavaScript String CheatSheet

The startsWith() the method determines whether a string begins with the characters of a specified string, returning true or false as appropriate.

const str1 = ‘Saturday night plans’;

console.log(str1.startsWith(‘Sat’));
// expected output: true

The endsWith() the method determines whether a string begins with the characters of a specified string, returning true or false as appropriate.

const str1 = ‘Cats are the best!’;

console.log(str1.endsWith(‘best’, 17));
// expected output: true

const str2 = ‘Is this a question’;

console.log(str2.endsWith(‘?’));
// expected output: false

The indexOf() the method returns the index within the calling String the object of the first occurrence of the specified value, starting the search at fromIndex. Returns -1 if the value is not found.

const paragraph = ‘The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?’;

const searchTerm = ‘dog’;
const indexOfFirst = paragraph.indexOf(searchTerm);

The slice() the method extracts a section of a string and returns it as a new string, without modifying the original string.

const str = ‘The quick brown fox jumps over the lazy dog.’;

console.log(str.slice(31));
// expected output: “the lazy dog.”

The substr() the method returns a portion of the string, starting at the specified index and extending for a given number of characters afterward.

const str = ‘Mozilla’;

console.log(str.substr(1, 2));
// expected output: “oz”

console.log(str.substr(2));
// expected output: “zilla”

The split() method divides a String into an ordered list of substrings, puts these substrings into an array, and returns the array. The division is done by searching for a pattern; where the pattern is provided as the first parameter in the method's call.

const str = ‘The quick brown fox jumps over the lazy dog.’;

consol.log(str.split(“ ”));

output: [“The”, “quick”, “brown”, “fox”, “jumps”, “over”, “the”, “lazy”, “dog.”]

The trim() the method removes whitespace from both ends of a string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator characters (LF, CR, etc.).

const greeting = ‘ Hello world! ‘;

console.log(greeting);
// expected output: “ Hello world! “;

console.log(greeting.trim());
// expected output: “Hello world!”;

I’m Md Nimur Hasan, a MERN Stack Developer. I know MongoDB, express, react, node js, and continue deep learning on these.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store