JavaScript Reference: String
By Flavio Copes
A current reference to JavaScript strings, including Unicode behavior, static String methods, and common instance methods for searching and transforming text.
JavaScript strings are immutable sequences of UTF-16 code units.
String indexes and length count UTF-16 code units, not necessarily user-perceived characters. The MDN String reference explains the Unicode details.
Call String() without new to convert a value to a string:
String(42) //'42'
Static methods
The String object has three static methods.
String.fromCharCode() creates a string from UTF-16 code units:
String.fromCharCode(70, 108, 97, 118, 105, 111) //'Flavio'
String.fromCodePoint() creates a string from Unicode code points:
String.fromCodePoint(70, 108, 97, 118, 105, 111) //'Flavio'
This matters for characters outside the basic multilingual plane:
String.fromCodePoint(0x1F436) //'🐶'
String.raw() returns the raw text of a tagged template literal:
String.raw`line 1\nline 2` //'line 1\\nline 2'
All other methods below are instance methods. JavaScript temporarily wraps a string primitive so you can call them directly.
Instance methods
A string offers many methods. The most commonly used are:
at(i)charAt(i)charCodeAt(i)codePointAt(i)concat(str)endsWith(str)includes(str)indexOf(str)lastIndexOf(str)localeCompare()match(regex)matchAll(regex)normalize()padEnd()padStart()repeat()replace(str1, str2)replaceAll(str1, str2)search(regexp)slice(begin, end)split(separator)startsWith(str)substring()toLocaleLowerCase()toLocaleUpperCase()toLowerCase()toString()toUpperCase()trim()trimEnd()trimStart()valueOf()isWellFormed()toWellFormed()
Strings are immutable. These methods return new strings instead of changing the original value:
const name = 'Flavio'
const upper = name.toUpperCase()
name //'Flavio'
upper //'FLAVIO'
Avoid the old HTML wrapper methods such as bold() and fontcolor(). They are deprecated. Use HTML and CSS instead.
Related posts about js: