LANGUAGE » JAVASCRIPT

String

Usage

js
let str1 = 'Some string'
let str2 = `Value of a is ${a}`  // Template string [ES6]
MethodReturnsDescription
charAtstringGet character from index.
startsWithbooleanChecks whether a string starts with the characters of pattern.
endsWithbooleanChecks whether a string ends with the characters of pattern.
includesbooleanDetermine whether a given string may be found within this searchString.
indexOfnumberGet the index of the first occurrence of the specified searchString.
matcharrayFind matching results (with g flag) or captured groups (without g flag) with the given regex.
padEndstringPads length from end with the given string.
padStartstringPads length from start with the given string.
replacestringReplace first match (if pattern is string) or all matches (if pattern is regex) with replacement.
searchnumberSame as indexOf, but uses regex as parameter.
slicestringSame as, for example, text[5:10] in python.
splitarraySplits by separator.
toLowerCasestringConvert to lower case.
toUpperCasestringConvert to upper case.
trimstringRemove whitespace from both ends.

Examples

Split by lines:

js
const lines = text.split(/\r?\n/);

Replace all:

js
text.replace(/-/g, '');  // Must have the g option
text.split('-').join('');

Capitalize:

js
text.charAt(0).toUpperCase() + text.slice(1);

Add zeros to the left of a number:

js
String(1).padStart(2, '0');  // "01"