LanguagesJavaScriptJavaScript String Methods for Concatenation and Substitution

JavaScript String Methods for Concatenation and Substitution

JavaScript tutorial

Welcome to the third and final article in our series on JavaScript string methods. The JavaScript Methods for Searching Strings tutorial presented the complete list of JavaScript (JS) methods for working with strings, along with detailed explanations of JavaScript’s eight string searching methods. In the last article, we looked at methods for trimming, padding, and extracting strings. This installment will cover how to concatenate strings, replace part of a string, change its case, and a whole lot more!

You can check out the previous two parts in this series here:

How to Concatenate Strings in JavaScript

Concatenation is the process of appending one string to the end of another string. You are probably already familiar with the + string concatenation operator. The difference is that concat () coerces its arguments directly to String objects, while + coerces its operands to primitives first.

Syntax of concat () in JavaScript

string.concat (str1)
string.concat (str1, str2)
string.concat (str1, str2, /* ..., */ strN)

Examples of concat () in JavaScript

const greeting = "Hi ";
// Outputs "Hi Rob. Have a good one!"
console.log(greeting.concat("Rob", ". Have a good one."));

const greetList = ["Rob", " and ", "George", "!"];
// Outputs "Hi Rob and George!"
console.log(greeting.concat(...greetList));

//Type conversion
"".concat ({}); // "[object Object]"
"".concat ([]); // ""
"".concat (null); // "null"
"".concat (true); // "true"
"".concat (6, 7); // "67"

How to Replace Text in JavaScript

To replace text in a JavaScript string, web developers have two choices: the replace() and replaceAll() methods. Both methods search a string for a specific string or regular expression. The replace() method substitutes the first match with the specified value and returns it as a new string. Meanwhile, as the name suggests, replaceAll() replaces all matches.

Syntax of replace() and replaceAll()

string.replace(pattern, replacement)
string.replaceAll(pattern, replacement)

Examples of replace() and replaceAll()

In practice, both methods are virtually identical, because replaceAll() will not replace all matches unless you use a RegEx for the pattern and include the g flag. As seen in the examples below, doing so with replace() will yield the same results!

let str = 'I studied at the School of Rock as well as the school of life!';
// Using an exact string pattern
console.log(str.replace('School', 'Institute'));
// Case insensitive
console.log(str.replace(/school/i, 'Institute'));
// Replaces ALL occurences
console.log(str.replace(/school/ig, 'Institute'));
// Replaces ALL occurences using replaceAll()
console.log(str.replaceAll(/school/ig, 'Institute'));
// Throws a TypeError because the g flag is required when using replaceALL()
console.log(str.replaceAll(/school/i, 'Institute'));

Note that replaceAll() is an ES2021 feature and does not work in Internet Explorer.

Read: Best Online Courses to Learn JavaScript

How to Change Case in JavaScript

You can convert a string to upper and lower case using the toUpperCase() and toLowerCase() methods, respectively.

Syntax of toLowerCase() and toUpperCase()

Neither method accepts parameters, so they are very simple to use:

string.toUpperCase()
string.toLowerCase()

Examples of toLowerCase() and toUpperCase()

const sentence = 'Robert likes to eat at The Greasy Spoon Diner.';
// Output: "robert likes to eat at the greasy spoon diner."
console.log(sentence.toLowerCase());

// Output: "ROBERT LIKES TO EAT AT THE GREASY SPOON DINER."
console.log(sentence.toUpperCase());

Working with Characters and Unicode in JavaScript

JavaScript strings are based on Unicode, with each character being represented by a byte sequence of 1-4 bytes. Therefore, JavaScript offers a number of methods to work with individual characters and bytes.

Here is a recap of JavaScript’s methods for working with characters and Unicode:

  • charAt(): returns character at a specified index in string
  • charCodeAt(): returns Unicode of the character at given index
  • fromCharCode(): returns a string from the given UTF-16 code units
  • codePointAt(): returns the Unicode point value at given index
  • fromCodePoint(): returns a string using the given code points

Syntax of JavaScript Unicode Methods

string.charAt(index)
string.charCodeAt(index)
string.codePointAt(index)
String.fromCharCode(n1, n2, ..., nX)
String.fromCodePoint(n1, n2, ..., nX)

charAt(), charCodeAt(), and codePointAt() all accept an integer between 0 and the string length minus 1. If the index cannot be converted to the integer or no index is provided, the default is 0 and the first character of the string is returned.

The fromCharCode() and fromCodePoint() methods are both static; fromCharCode() accepts a sequence of Unicode code points, while fromCodePoint() accepts one or more Unicode values to be converted.

Examples of Unicode Methods

const str = "Outside my window there’s an open road";
// charAt() ***********************************************
// No index was provided, used 0 as default
console.log(str.charAt()); // O
// Explicitly providing 0 as index
console.log(str.charAt(0)); // O
console.log(str.charAt(3)); // s
console.log(str.charAt(999)); // ""

// charCodeAt() *******************************************
// No index was provided, used 0 as default
console.log(str.charCodeAt()); // 79
// Explicitly providing 0 as index
console.log(str.charCodeAt(0)); // 79
console.log(str.charCodeAt(3)); // 115
console.log(str.charCodeAt(999)); // NaN

// codePointAt() *******************************************
"ABC".codePointAt(0); // 65
"ABC".codePointAt(0).toString(16); // 41

"😍".codePointAt(0); // 128525
"ud83dude0d".codePointAt(0); // 128525
"ud83dude0d".codePointAt(0).toString(16); // 1f60d
"😍".codePointAt(1); // 56845
"ud83dude0d".codePointAt(1); // 56845
"ud83dude0d".codePointAt(1).toString(16); // de0d

"ABC".codePointAt(40); // undefined

// fromCharCode() ******************************************
// Outputs "½+¾="
console.log(String.fromCharCode(189, 43, 190, 61));

// fromCodePoint() *****************************************
// Outputs "☃★♲你"
console.log(String.fromCodePoint(9731, 9733, 9842, 0x2F804));

Read: Top Collaboration Tools for Web Developers

Miscellaneous String Methods in JavaScript

A couple of String methods do not fall into any of the above categories. They are localeCompare(), which compares two strings in the current locale, and repeat(), which returns a string by repeating it given times. Let’s take a look at each of them.

localeCompare() Syntax

localeCompare(compareString)
localeCompare(compareString, locales)
localeCompare(compareString, locales, options)

Of the three input parameters above, only the compareString is required.

The locales should be a string, or array of strings, with a BCP 47 language tag.

The options are an object that adjust the output format.

Examples of localeCompare()

// The letter "a" is before "c" resulting in a negative value
"a".localeCompare("c"); // -2 or -1 (or some other negative value)

// Alphabetically the word "check" comes after "against" resulting in a positive value
"check".localeCompare("against"); // 2 or 1 (or some other positive value)

// "a" and "a" are equivalent resulting in a neutral value of zero
"a".localeCompare("a"); // 0

console.log("ä".localeCompare("z", "de")); // a negative value: in German, ä sorts before z
console.log("ä".localeCompare("z", "sv")); // a positive value: in Swedish, ä sorts after z

// in German, ä has a as the base letter
console.log("ä".localeCompare("a", "de", { sensitivity: "base" })); // 0
// in Swedish, ä and a are separate base letters
console.log("ä".localeCompare("a", "sv", { sensitivity: "base" })); // a positive value

repeat() Syntax

The repeat() method’s one input parameter is an integer of 0 or above, indicating the number of times to repeat the string. Passing in a negative number results in a RangeError.

repeat(count)

Examples of repeat() Method

"abc".repeat(-1); // RangeError
"abc".repeat(0); // ''
"abc".repeat(1); // 'abc'
"abc".repeat(2); // 'abcabc'
"abc".repeat(3.5); // 'abcabcabc' (count will be converted to integer)
'abc'.repeat(1 / 0); // RangeError

You will find a demo of today’s methods on Codepen.io.

Final Thoughts on JavaScript String Methods for Concatenation and Substitution

In this third and final web development tutorial in our series on JavaScript string methods, we learned how to concatenate strings, replace part of a string, change its case, and a whole lot more. All of the methods presented here today should work in all modern browsers, unless otherwise indicated.

Read more web development and JavaScript programming tutorials.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories