LANGUAGE » JAVASCRIPT

String

Usage

js
let str1 = 'Some string'
let str2 = `Value of a is ${a}`  // Template string [ES6]
MethodParamsReturn typeDescription
charAtindexstringGet character from index.
endsWithpatternbooleanChecks whether a string ends with the characters of this string.
includessearchStringbooleanDetermine whether a given string may be found within this string.
indexOfsearchStringnumberGet the index of the first occurrence of the specified substring.
matchregexarrayFind matching results (with g flag) or captured groups (without g flag).
padEndtargetLen padStringstringPads this string from end with the given string.
padStarttargetLen padStringstringPads this string from start with the given string.
replacepattern replacementstringReplace first match (if pattern is string) or all matches (if pattern is regex).
searchregnumberSame as indexOf, but uses regex as parameter.
slicebeginIndex endIndexstringSame as, for example, text[5:10] in python.
splitseparraySplits 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"