HomeTutorsContact

How to replace all occurrences in string using JavaScript?

By Gulshan Saini
Published in JavaScript
June 18, 2020
1 min read

Say you have following string and we want to replace all spaces in above string with hyphen (-).

How to replace all occurrences in string using JavaScript?

Let’s explore different ways to replace all occurrences using JavaScript.

Using String.prototype.split() and Array.prototype.join()

In the first solution we are first going to split the string and convert it into an array and then use join() method to combine all array items separated by a hyphen.

split() method accepts separator(optional) as an argument. In our case, it’s going to be space " "

let title = 'How to replace all occurrences in string using JavaScript?'

// split the string into an array
let titleArray = title.split(' ')

If we log the titleArray on console it would print

Output

console.log(titleArray);
["How", "to", "replace", "all", "occurrences", "in", "string", "using", "JavaScript?"]

Next, we use join() method that accepts separator(optional) as an argument. In our case, it’s going to be hyphen "-". We can update the title variable again to store new hyphenated value.

// join back the titleArray using hyphen and update title variable
title = titleArray.join('-')

If we log the title on console it would print

Output

console.log(title);
"How-to-replace-all-occurrences-in-string-using-JavaScript?"

Using replace() global expression

replace() function directly available on String accepts a regular expression as the first argument and replacement string as the second argument. The syntax is as follows.

str.replace(regexp, newString)

The regexp is going to be /\s/g where, \s selects single space in a string and g is used to search globally.

Tip: Say you have string with double spaces in between of words we would replace '/\s/g' with '/\s+/g' - notice the plus(+) sign.

let title = 'How to replace all occurrences in string using JavaScript?'

// replace all spaces with hyphen using regexp
title = 'How to replace all occurrences in string using JavaScript?'.replace(
  /\s/g,
  '-'
)

If we log the title on console it would print

Output

console.log(title);
"How-to-replace-all-occurrences-in-string-using-JavaScript?"

Tags

#javascript
Previous Article
How to print all the properties of the object in JavaScript?

Related Posts

JavaScript
How to check if a string contains a substring in JavaScript?
January 05, 2021
1 min
Gulshan Saini

Gulshan Saini

Fullstack Developer

Topics

Flutter
JavaScript
NextJS
ReactJS
Typescript

Subscribe to our newsletter!

We'll send you the best of our blog just once a month. We promise.
© 2021, All Rights Reserved.

Quick Links

Contact UsBrowserCSSPythonPuppeteer

Social Media