JavaScript

String Methods

Strings are immutable: Strings cannot be changed, only replaced. All string methods return a new string. They don't modify the original string.


Extracting String Parts

Javascript counts position from 0. Then, last position will be text.length-1.

There are 3 methods to extract parts of a string:

Slice

text.slice(start)
text.slice(start, end)

The first parameter marks the start position, the second parameter marks the end position to slice prior to (end position not included).

let text = "Kitten sings a song.";
let part = text.slice(7, 12);    // "sings"
K  i  t  t  e  n  _    s  i  n  g  s    _  a  _  s  o  n  g  .  
0  1  2  3  4  5  6    7  8  9 10 11    12 13 14 15 16 17 18 19

If the parameter is negative, the position is counted from the end of the string, started from 0.

let text = "Kitten sings a song.";
let part;
part = text.slice(-13, -8);  // "sings"
part = text.slice(7, -8);    // "sings"
  K   i   t   t   e   n   _      s   i   n   g   s      _   a   _   s   o   n   g   .  
-20 -19 -18 -17 -16 -15 -14    -13 -12 -11 -10  -9     -8  -7  -6  -5  -4  -3  -2  -1

If there's only one parameter, it's considered the starting parameter and will slice to the end of the string

let text = "Kitten sings a song.";
let part;
part = text.slice(7);        // "sings a song."
part = text.slice(-13);      // "sings a song."

Substring

text.substring(start)
text.substring(start, end)

Very similar to slice(), but can't accept negative parameter.

let text = "Kitten sings a song.";
let part;
part = text.substring(7, 12);    // "sings"
part = text.substring(7);        // "sings a song."
part = text.substring(-13, -8);  // ""
part = text.substring(-13);      // "Kitten sings a song."

Backward substring(end, start) works, with identical result with substring(end, start). This is not possible in slice().

let text = "Kitten sings a song.";
let part;
part = text.substring(7, 12);    // "sings"
part = text.substring(12, 7);    // "sings a song."
part = text.slice(12, 7);        // ""

Substr

text.substr(start)
text.substr(start, length)

substr()is also similar to slice(), but the second parameter is string length instead of end position. Just like slice(), without the second parameter, it will slice to the end of the string, and negative first parameter will count starting position from end of the string. Negative length will just mean to length.

let text = "Kitten sings a song.";
let part;
part = text.substr(7, 5);    // "sings"
part = text.substr(7);       // "sings a song."
part = text.substr(-13, 5);  // "sings a song."
part = text.substr(-13);     // "sings a song."
part = text.substr(-13, 0);  // ""
part = text.substr(-13, -1); // ""

Replacing String Content

text.replace(current, new)

replace() is like find and replace function.

let text = "Kitten sings a song.";
let newText;
newText = text.replace("Kitten", "Pup"); // "Pup sings a song."
newText = text.replace("sing", "play");  // "Kitten plays a song."

Global Match /g

replace() only changes the first match. To replace all matches, use regular expression with a /g flag (global match). Regular expressions are written without quotes.

let triple = "Kitten one, Kitten two, Kitten three!";
let newTriple;
newTriple = triple.replace("Kitten", "Pup");    // "Pup one, Kitten two, Kitten three!"
newTriple = triple.replace(/Kitten/g, "Pup");   // "Pup one, Pup two, Pup three!"

Case Insensitive /i

replace() is case sensitive. To replace case insensitive, use a regular expression with an /i flag (insensitive).

let text = "Kitten sings a song.";
let newText;
newText = text.replace("kitten", "Pup");    // "Kitten sings a song."
newText = text.replace(/kitten/i, "Pup");   // "Pup sings a song."

More on regular expressions: w3schools - JS Regular Expressions


Converting to Lower and Upper Case

text.toUpperCase()
text.toLowerCase()
let text = "Kitten sings a song.";
let newText;
newText = text.toUpperCase(); // "KITTEN SINGS A SONG."
newText = text.toLowerCase(); // "kitten sings a song."
text.toLocaleUpperCase()
text.toLocaleLowerCase()

These 2 are similar to lowercase and uppercase above, except for locales that conflict with the regular Unicode case mappings (such as Turkish).


Concatenating Strings

text.concat(string1, string2, and so on)
let animal1 = "cat";                            // "cat"
let animal2 = "dog";                            // "dog"
let animal3;
animal3 = animal1.concat(" and ", animal2); // "cat and dog"
animal3 = animal1 + " and " + animal2; // "cat and dog"

Trimming Strings

text.trim()

trim() removes whitespace from both sides of a string.

let text = "    Kitten     ";
let cleanText = text.trim();    // "Kitten"

Padding Strings

text.padStart(targetLength)
text.padStart(targetLength, padString)

text.padEnd(targetLength)
text.padEnd(targetLength, padString)

Use padStart() to add padding to the beginning of a text, and padEnd() to the end of a text. The first parameter is the new text target length, and the second parameter is the filler fo the pad. If there's only 1 parameter, the filler will be whitespace.

let text = "KITTEN";
let padded;
padded = text.padStart(12,"*-");    // "*-*-*-KITTEN"
padded.length;                      // 12
padded = text.padStart(12);         // "      KITTEN"
padded = text.padEnd(12,"*-");      // "KITTEN*-*-*-"

Exercise: Let's change the first 12 digits of credit card with *

let realNumber = "0000111100006789";
let safeNumber = (realNumber.slice(-4)).padStart(16, "*"); 
safeNumber;     // "************6789"

More legible writing:

let realNumber  = "0000111100006789";
let shortNumber = realNumber.slice(-4);
let safeNumber  = shortNumber.padStart(16, "*"); 
safeNumber;     // "************6789"

Extracting String Characters

text.charAt(index)

The charAt() method returns the character at a specified index (position) in a string.

let text = "Kitten";
let char = text.charAt(1); // "i"
text.charCodeAt(index)

The charCodeAt() method returns unicode of the character at a specified index in a string.

let text = "Kitten";
let char = text.charAt(1); // 105

Property Access []

text[index]
let text = "Kitten";
let char = text[1]; // "i"

When no character is found, charAt() returns an empty string "", while property access [] returnes undefined.

let text = "Kitten";
let char;
char = text.charAt(6);  // ""
char = text[6];         // undefined

Property access [] is read only, we can't change the text's character using this. It gives no error, but it doesn't work.

let text = "Kitten";
text[1];                // "i"
text[1] = "o";          // "o"
text[1];                // "i"
text;                   // "Kitten"

Converting a String to an Array

Property access [] makes a string looks like an array, but it's not.

A string can be converted to an array with the split() method. Inside the bracket is the separator. The string will be splitted on this separator.

text.split()

Without any separator, the whole string will be put in [0].

let text = "cat and dog";
llet array = text.split();
array;          // ['cat and dog']
array.length;   // 1
text.length;    // 11
array[0];       // 'cat and dog'
array[1];       // undefined
text.split("")

With an empty quote as the separator "", each character will be separated into elements. The variable length and index content will be the same with the original string.

let text = "cat and dog";
let array = text.split("");
array;          // (11) ['c', 'a', 't', ' ', 'a', 'n', 'd', ' ', 'd', 'o', 'g']
text.split(",")
text.split(" ")
text.split("|")

These are some common separators. The string will be splitted at commas, spaces, or pipes. So which one to use will depend on the string source.

let zoo = "cat dog cow pig fox";
let animal;

animal = zoo.split(" ");    // Use space separator
animal;                     // (5) ['cat', 'dog', 'cow', 'pig', 'fox']

animal = zoo.split(",");    // Don't use comma separator
animal;                     // ['cat dog cow pig fox']

Example of using other separator

let zoo = "cat, dog, cow, pig, fox";
let animal;

animal = zoo.split(",");    // Using comma separator
animal;                     // (5) ['cat', ' dog', ' cow', ' pig', ' fox']

animal = zoo.split(", ");   // Use "comma-space" separator
animal;                     // (5) ['cat', 'dog', 'cow', 'pig', 'fox']

Fun practise: Using split() to count characters, words, or sentences.

loremIpsum = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";

console.log(`About Lorem Ipsum`);
console.log(`Character count: ${loremIpsum.length}`);
console.log(`Word count: ${(loremIpsum.split(" ")).length}`);
console.log(`Sentence count: ${(loremIpsum.split(".")).length-1}`);
Results:
About Lorem Ipsum
Character count: 445
Word count: 69
Sentence count: 4

Checking for Values inside Content

text.includes("value")

Returns true if a string contains the specified value.

let animal = "Kitten and Doggie are best friends."
animal.includes("friends");     // true
animal.includes("kitten");      // false
animal.includes("g c");         // true
text.startsWith("value")

Returns true if a string starts with the specified value.

let animal = "Kitten and Doggie are best friends."
animal.startsWith("Dog");       // false
animal.startsWith("kitten");    // false
animal.startsWith("K");         // true
text.endsWith("value")

Returns true if a string ends with the specified value.

let animal = "Kitten and Doggie are best friends."
animal.endsWith("friends");     // false
animal.endsWith(".");           // true
animal.endsWith("ds.");         // true

For includes(), startsWith(), and endsWith(), the content searched must be a string "__", can't be a regular expression /__/.


Searches with Index Returns

text.indexOf("value")

indexOf() returns the index (position) of the first occurrence of a value in a string.

text.lastIndexOf("value")

lastIndexOf() returns the index (position) of the last occurrence of a value in a string. The method searches the value from the end of the string to the beginning.

For both methods:

let text = "Mr. Brown's hair is brown."
text.indexOf("brown");      // 20
text.indexOf(/brown/);      // -1
text.lastIndexOf("brown");  // 20
text.lastIndexOf(/brown/);  // -1
text.lastIndexOf("own");    // 22
text.indexOf("own");        // 6

Searches using Regular Expression

text.search(/value/)
text.search("value")

search() searches a regular expression, and returns the index (position) of the first match.

let text = "Mr. Brown's hair is brown."
text.search("brown");   // 20
text.search(/brown/i);  // 4
text.search(/mr/);      // -1
text.match(/value/)
text.match("value")

match() finds all matches and displays them in array.

let text = "Mr. Brown's hair is brown."
text.match("brown");    // ['brown', index: 20, input: "Mr. Brown's hair is brown.", groups: undefined]
text.match(/brown/i);   // ['Brown', index: 4, input: "Mr. Brown's hair is brown.", groups: undefined]
text.match(/brown/ig);  // (2) ['Brown', 'brown']
text.match(/BROWN/);    // null

Comparing 2 Strings

text1.localeCompare(text2)

localeCompare() compares two strings in the current locale. It returns 1 of 3 possible numbers indicating the sort order:

let text1 = "aaa";
let text2 = "bbb";
let text3 = "aaa";
let text4 = "AAA";
let text5 = "123";
let text6 = "";
let text7 = 1;
text1.localeCompare(text2);     // -1
text1.localeCompare(text3);     // 0
text1.localeCompare(text4);     // -1
text1.localeCompare(text5);     // 1
text1.localeCompare(text6);     // 1
text1.localeCompare(text7);     // 1

Create Repeat String

text1.repeat(count)

repeat() returns a new string with a number of copies of a string.

let text1 = "Kitten";
let text2;
text2 = text1.repeat(3);        // "KittenKittenKitten"
text2 = text1.repeat(1);        // "Kitten"
text2 = text1.repeat(0);        // ""
text2 = text1.repeat();         // ""
text2 = text1.repeat(-1);       // error, invalid count value

Convert a String Object into a String

text1.toString()

toString() returns a string. It can be used to change string object or number into string.

let text1 = "cow";
let text2;
text2 = new String(text1);      // making string object
text2 = new String("cow");      // or directly
text2;                          // String {"cow"}
typeof text2;                   // object
let text3 = text2.toString();
text3;                          // "cow"
typeof text3;                   // string

text2 = 123;                    // 123
typeof text2;                   // number
let text3 = text2.toString();
text3;                          // "123"
typeof text3;                   // string
text1.valueOf()

valueOf() returns the primitive value of a string. If the string is already a primitive string, then there's no change. It can be used to convert a string object into a string. Normally we don't need to use this. It is used internally by JavaScript. It can't be used to change number into string.

let text1 = "cow";
let text2;
text2 = new String(text1);      // making string object
text2 = new String("cow");      // or directly
text2;                          // String {"cow"}
typeof text2;                   // object
let text3 = text2.valueOf();
text3;                          // "cow"
typeof text3;                   // string

Convert Unicode Values into Characters

String.fromCharCode(n1, n2, ..., nX)

fromCharCode() returns Unicode values as characters

let text = String.fromCharCode(65);
text;           // "A"
let text = String.fromCharCode(72, 69, 76, 76, 79);
text;           // "HELLO"