Member-only story
How To Manipulate Strings in JavaScript
Combine and repeat strings, change cases, remove whitespace, and more

JavaScript has built-in functions and constructs to do most string operations. The ones that don’t can be done with a few simple function calls.
Combine Strings
Concatenation
There are two ways to do it. One way is to use the concat
function.
For example:
const hello = "Hello ";
const bob = "Bob!";
const res = hello.concat(bob); // Hello Bob!
Another way is to use the +
operator, like so:
const hello = "Hello ";
const bob = "Bob!";
const res = hello + bob; // Hello Bob!
Template strings
ES6 or later has template strings so you can include strings within another string, like this:
const hello = "Hello ";
const bob = "Bob!";
const res = `${hello} ${bob}`; // Hello Bob!
Array.join
If you have an array of strings, you can combine the entries with the same separator between them, with the join
function, like this:
const arr = ['Hello', 'Bob'];
const res = arr.join(' '); // 'Hello Bob'
Get Substring
String.substr
JavaScript strings have a substr
function to get the substring of a string.
It takes a starting index as the first argument and a number of characters from the start index, and so on as the second argument.
It can be used like this:
const str = "Hello Bob";
const res = str.substr(1, 4); // ello
String.substring
JavaScript strings also have a substring
function that takes the start and end index as two arguments and returns a string with the ones between the start and end indices.
The start index is included but the end index is excluded.
Example:
const str = "Hello Bob";
const res = str.substring(1, 3); // el