replace - with space

Replace - with Space

Have you ever come across a situation where you have a string with some hyphens in it and you want to replace those hyphens with spaces? It can be a tricky task if you don't know the right way to do it.

Using String.prototype.replace()

The easiest way to replace hyphens with spaces is by using the replace() method that is available on every string in JavaScript. The replace() method takes two arguments: the first argument is the pattern to search for (in our case, the hyphen character) and the second argument is the replacement string (in our case, a space character).

const originalString = "This-is-a-string-with-hyphens";
const replacedString = originalString.replace(/-/g, " ");
console.log(replacedString); // Output: This is a string with hyphens

In the above example, we first define a string that contains hyphens. We then use the replace() method to replace all instances of the hyphen character with a space character. We use a regular expression with the global flag (/-/g) to match all hyphens in the string.

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

Another way to replace hyphens with spaces is by using the split() and join() methods. We can first split the string into an array of strings using the hyphen character as the delimiter, and then join the array back together with a space character as the separator.

const originalString = "This-is-a-string-with-hyphens";
const splitString = originalString.split("-");
const replacedString = splitString.join(" ");
console.log(replacedString); // Output: This is a string with hyphens

In the above example, we first define a string that contains hyphens. We then use the split() method to split the string into an array of strings. We use the hyphen character as the delimiter. We then use the join() method to join the array back together with a space character as the separator.

Conclusion

Replacing hyphens with spaces is a common task that you may need to do in your JavaScript projects. The replace() method and the split() and join() methods can both be used to accomplish this task. Choose the method that you find most readable and maintainable for your particular use case.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe