DEV Community

Cover image for The only JavaScript "String" Guide you will Ever Need.
Vedant Chainani
Vedant Chainani

Posted on

The only JavaScript "String" Guide you will Ever Need.

Strings

Strings can be created as primitives, from string literals, or as objects, using the String() constructor:

const string1 = "A string primitive";
const string2 = 'Also a string primitive';
const string3 = `Yet another string primitive`;

const string4 = new String("A String object");
Enter fullscreen mode Exit fullscreen mode

String literals can be specified using single or double quotes, which are treated identically, or using the backtick character. This last form specifies a template literal: with this form you can interpolate expressions.


Finding the length of a string

const myStr = 'Hello World!';
console.log(myStr.length); // 12
Enter fullscreen mode Exit fullscreen mode

Retrieving a specific string character

const myStr = 'Hello World!';
console.log(myStr[2]); // l
Enter fullscreen mode Exit fullscreen mode

Remember: computers count from 0, not 1!

To retrieve the last character of any string, we could use the following line, combining this technique with the length property we looked at above:

const myStr = "Hello World!";
console.log(myStr[myStr.length - 1]); // !
Enter fullscreen mode Exit fullscreen mode

Static methods

String.fromCharCode()

Returns a string created by using the specified sequence of Unicode values

Syntax -

String.fromCharCode(num1)
String.fromCharCode(num1, num2)
String.fromCharCode(num1, num2, /* …, */ numN)
Enter fullscreen mode Exit fullscreen mode

Parameters -
A sequence of numbers that are UTF-16 code units. The range is between 0 and 65535 (0xFFFF). Numbers greater than 0xFFFF are truncated. No validity checks are performed.

This method returns a string and not a String object.

Example -

console.log(String.fromCharCode(72, 69, 76, 76,79)); // "HELLO"
Enter fullscreen mode Exit fullscreen mode

String.raw()

Returns a string created from a raw template string.

// Create a variable that uses a Windows
// path without escaping the backslashes:
const filePath = String.raw`C:\Users\vedan\Desktop\index.js`;

console.log(`The file was uploaded from: ${filePath}`);
// Output - The file was uploaded from: C:\Users\vedan\Desktop\index.js
Enter fullscreen mode Exit fullscreen mode

Instance methods

String.at()

Returns the character (exactly one UTF-16 code unit) at the specified index. Accepts negative integers, which count back from the last string character.

const myStr = "Hello world!";
console.log(myStr.at(4)); // o
console.log(myStr.at(-2)); // d
Enter fullscreen mode Exit fullscreen mode

String..charAt()

Same as String.at() but charAt() does not accept negative index.

const myStr = "Hello world!";
console.log(myStr.charAt(4)); // o
console.log(myStr.charAt(-2)); // 
Enter fullscreen mode Exit fullscreen mode

If Negative index is provided it does not return anything.


String.charCodeAt(index)

Returns a number that is the UTF-16 code unit value at the given index.

If index is out of range, charCodeAt() returns NaN.

const myStr = "Hello world!";

console.log(
  `The character code ${myStr.charCodeAt(2)} is equal to ${myStr.charAt(2)}`
);

// Output - The character code 108 is equal to l
Enter fullscreen mode Exit fullscreen mode

String.concat()

The concat() function concatenates the string arguments to the calling string and returns a new string. Changes to the original string or the returned string don't affect the other.

If the arguments are not of the type string, they are converted to string values before concatenating.

const myStr = "Hello world";
const concatStr = "".concat("My ", 1, "st ", myStr, " Program!");
console.log(concatStr); // My 1st Hello world Program!
Enter fullscreen mode Exit fullscreen mode

String.includes()

This method lets you determine whether or not a string includes another string.The includes() method is case sensitive.

const myStr = "Hello world";
console.log(myStr.includes("Hello")); // true
console.log(myStr.includes("hello")); // false
Enter fullscreen mode Exit fullscreen mode

String.startsWith(searchString,position)

This method lets you determine whether or not a string begins with another string. This method is case-sensitive.

It also takes a optional argument position
The position in this string at which to begin searching for searchString. Defaults to 0.

const myStr = "Hello world";
console.log(myStr.startsWith("Hello")); // true
Enter fullscreen mode Exit fullscreen mode

String.endsWith(searchString,position)

This method lets you determine whether or not a string ends with another string. This method is case-sensitive.

const myStr = "Hello world";
console.log(myStr.endsWith("world")); // true
Enter fullscreen mode Exit fullscreen mode

String.indexOf()

The indexOf() method, given one argument: a substring to search for, searches the entire calling string, and returns the index of the first occurrence of the specified substring. Given a second argument: a number, the method returns the first occurrence of the specified substring at an index greater than or equal to the specified number.

const sentence = "Hi! I am Vedant. I like to code.";

let firstOccurrence = sentence.indexOf("I");
let secondOccurrence = sentence.indexOf("I", firstOccurrence + 1);

console.log(
  `First Occurrence: ${firstOccurrence} , second Occurrence: ${secondOccurrence}`
);

// First Occurrence: 4 , second Occurrence: 17
Enter fullscreen mode Exit fullscreen mode

String.lastIndexOf()

The lastIndexOf() method, given one argument: a substring to search for, searches the entire calling string, and returns the index of the last occurrence of the specified substring. Given a second argument: a number, the method returns the last occurrence of the specified substring at an index less than or equal to the specified number.

const sentence = "Hi! I am Vedant. I like to code.";
console.log(sentence.lastIndexOf("I")); // 17
Enter fullscreen mode Exit fullscreen mode

String.match()

Used to match regular expression regexp against a string.
Regular expressions are patterns used to match character combinations in strings. In JavaScript, regular expressions are also objects.

const paragraph =
  "Cucumbers, spinach, broccoli and onions are considered non-starchy Vegetables.";
const regex = /[A-Z]/g; 
// This regex is used to match all Capital Case Alphabet characters Globally.
const found = paragraph.match(regex);

console.log(found); // [ 'C', 'V' ]
Enter fullscreen mode Exit fullscreen mode

String.normalize()

Unicode assigns a unique numerical value, called a code point, to each character. For example, the code point for "A" is given as U+0041. However, sometimes more than one code point, or sequence of code points, can represent the same abstract character — the character "ñ" for example can be represented by either of:

  • The single code point U+00F1.
  • The code point for "n" (U+006E) followed by the code point for the combining tilde (U+0303).
const string1 = '\u00F1';
const string2 = '\u006E\u0303';

console.log(string1);  //  ñ
console.log(string2);  //  ñ
Enter fullscreen mode Exit fullscreen mode

However, since the code points are different, string comparison will not treat them as equal. And since the number of code points in each version is different, they even have different lengths.

const string1 = '\u00F1';            // ñ
const string2 = '\u006E\u0303';      // ñ

console.log(string1 === string2); // false
console.log(string1.length);      // 1
console.log(string2.length);      // 2
Enter fullscreen mode Exit fullscreen mode

The normalize() method helps solve this problem by converting a string into a normalized form common for all sequences of code points that represent the same characters.

The function takes one argument form which is one of "NFC""NFD""NFKC", or "NFKD", specifying the Unicode Normalization Form. If omitted or undefined"NFC" is used.

const string1 = "\u00F1"; // ñ
const string2 = "\u006E\u0303"; // ñ

console.log(string1 === string2); // false

const normalizedString1 = string1.normalize("NFD");
const normalizedString2 = string2.normalize("NFD");

console.log(normalizedString1 === normalizedString2); // true
Enter fullscreen mode Exit fullscreen mode

String.padEnd(targetLength [, padString])

Pads the current string from the end with a given string and returns a new string of the length targetLength.

Parameters

targetLength -

The length of the resulting string once the current str has been padded. If the value is lower than str.length, the current string will be returned as-is.

padString -

The string to pad the current str with. The default value for this parameter is " " (U+0020).

const myStr = "Hello World";
console.log(myStr.padEnd(14,"!")); // Hello World!!!
Enter fullscreen mode Exit fullscreen mode

String.padStart(targetLength [, padString])

The padStart() method pads the current string with another string (multiple times, if needed) until the resulting string reaches the given length. The padding is applied from the start of the current string.

This also takes two arguments targetLength and padString same as String.padEnd().

const cardNumber = "4535901040373156";
const last4Digits = cardNumber.slice(-4);
console.log(last4Digits.padStart(16,"*")); // ************3156
Enter fullscreen mode Exit fullscreen mode

String.repeat()

Returns a string consisting of the elements of the object repeated count times.

const myStr = "Hello ";
console.log(myStr.repeat(3)); // Hello Hello Hello
Enter fullscreen mode Exit fullscreen mode

String.replace()

The replace() method returns a new string with one, some, or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function called for each match. If pattern is a string, only the first occurrence will be replaced. The original string is left unchanged.

const sentence = "How much wood would a woodchuck chuck if a woodchuck could chuck wood?";

console.log(sentence.replace("wood","water"));

// How much water would a woodchuck chuck if a woodchuck could chuck wood?
Enter fullscreen mode Exit fullscreen mode

String.replaceAll()

The replaceAll() method returns a new string with all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match. The original string is left unchanged.

const sentence = "How much wood would a woodchuck chuck if a woodchuck could chuck wood?";

console.log(sentence.replaceAll("wood", "water"));

// How much water would a waterchuck chuck if a waterchuck could chuck water?
Enter fullscreen mode Exit fullscreen mode

String.search()

The search() method executes a search for a match between a regular expression and this String object.

const myStr = "Hello World!"

// any character that is not a word character or whitespace
const regex = /[^\w\s]/g;

console.log(myStr.search(regex));         // 11
console.log(myStr[myStr.search(regex)]);  // !
Enter fullscreen mode Exit fullscreen mode

String.slice(indexStart, indexEnd)

slice() extracts the text from one string and returns a new string. Changes to the text in one string do not affect the other string.

slice() extracts up to but not including indexEnd. For example, str.slice(1, 4) extracts the second character through the fourth character (characters indexed 12, and 3).

If indexEnd is not specified then it goes till end of the string.

const myStr = "Hello World!";

console.log(myStr.slice(6)); // World!
Enter fullscreen mode Exit fullscreen mode

String.split()

The split() method takes a pattern and divides a String into an ordered list of substrings by searching for the pattern, puts these substrings into an array, and returns the array.

It takes two optional parameters-

  1. separator - The pattern describing where each split should occur.
  2. limit - A non-negative integer specifying a limit on the number of substrings to be included in the array. If provided, splits the string at each occurrence of the specified separator, but stops when limit entries have been placed in the array. Any leftover text is not included in the array at all.
const myStr = "Hi, I am Vedant";

console.log(myStr.split()); // [ 'Hi, I am Vedant' ]
console.log(myStr.split(" ")); // [ 'Hi,', 'I', 'am', 'Vedant' ]
console.log(myStr.split(" ", 2)); // [ 'Hi,', 'I' ]
Enter fullscreen mode Exit fullscreen mode

String.substring()

The substring() method returns the part of the string between the start and end indexes, or to the end of the string.

const myStr = "Hello World!";

console.log(myStr.substring(6, 11)); // World
Enter fullscreen mode Exit fullscreen mode

String.toLowerCase()

The toLowerCase() method returns the value of the string converted to lower case. toLowerCase() does not affect the value of the string str itself.

const myStr = "HelLo WoRld!";

console.log(myStr.toLowerCase()); // hello world!
Enter fullscreen mode Exit fullscreen mode

String.toUpperCase()

The toUpperCase() method returns the value of the string converted to uppercase. This method does not affect the value of the string itself since JavaScript strings are immutable.

const myStr = "HelLo WoRld!";

console.log(myStr.toUpperCase()); // HELLO WORLD!

Enter fullscreen mode Exit fullscreen mode

String.toString()

The toString() method of a string object returns a string representing the specified string.

const myStr = new String("Hello World");

console.log(myStr); // [String: 'Hello World']
console.log(myStr.toString()); // Hello World
Enter fullscreen mode Exit fullscreen mode

String.trim()

The trim() method removes whitespace from both ends of a string and returns a new string, without modifying the original 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 myStr = "  Hello World ";

console.log(myStr.trim()); // "Hello World"
Enter fullscreen mode Exit fullscreen mode

String.trimStart()

The trimStart() method removes whitespace from the beginning of a string. trimLeft() is an alias of this method.

const myStr = "  Hello World ";

console.log(myStr.trimStart()); // "Hello World "
Enter fullscreen mode Exit fullscreen mode

String.trimEnd()

The trimEnd() method removes whitespace from the end of a string. trimRight() is an alias of this method.

const myStr = "  Hello World ";

console.log(myStr.trimEnd()); // "  Hello World"
Enter fullscreen mode Exit fullscreen mode

String.valueOf()

The valueOf() method returns the primitive value of a String object.

const myStr = new String("Hello World");

console.log(myStr); // [String: 'Hello World']
console.log(myStr.valueOf()); // Hello World
Enter fullscreen mode Exit fullscreen mode


Top comments (0)