HomeTutorsContact
JavaScript
How to replace all occurrences in string using JavaScript?
Gulshan Saini
June 18, 2020
1 min

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

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 " "

If we log the titleArray on console it would print

Output

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.

If we log the title on console it would print

Output

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.

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.

If we log the title on console it would print

Output


Tags

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

Subscribe to our newsletter!

We'll send you the best of our blog just once a month. We promise.

Related Posts

How to Get Current Date in Human Readable Form in JavaScript?
October 03, 2020
1 min
© 2020, All Rights Reserved.

Quick Links

Advertise with usContact Us

Social Media