'How can we replace space in url with dash?

I am new to reactjs and working on a small project, What I want is to replace white space with dash(-) in url parameters. Anybody help me to achieve this.

Thanks in advance.



Solution 1:[1]

If you wanna to replace whitespace with dash then use following regex `let

let myString = "Stack Over Flow";
myString = myString.replace(/\s+/g, '-');

console.log(myString);`// Stack-Over-Flow

Solution 2:[2]

If you are using react-router for routing then you can replace the URL like:

let Url = props.history.location.pathname.replace(/ /g, '-');

By doing this, if your URL is "/questions/50443435/how can we replace space in url with dash"

Then the result will be

"/questions/50443435/how-can-we-replace-space-in-url-with-dash"

Solution 3:[3]

You can use string#replace with regular expression.

let str = "repace  space me with dash"

str.replace(/ /g,'-'); // g - replace all

Solution 4:[4]

Just add .replace(/ /g, "-") after the link parameters.

<Link to={/article/${article.title.replace(/ /g, "-")}}>Link </Link>

<a href={/article/${article.title.replace(/ /g, "-")}}>Link </a>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Himanshu Pandey
Solution 2 Hitesh Chaudhari
Solution 3 RIYAJ KHAN
Solution 4 Yamin Ooh