3

I'm using react and I came across a problem, albeit an aesthetic problem and not a functional one.

I am generating react-routes from an API of names. The route works fine, but as the names have spaces, they appear in the url as: example.com/lookup/David%20Attenborough

Example: <Link to='{/lookup/' + props.data.name}>{props.data.name}</Link>

Is there a clever way I can remove the spaces: example.com/lookup/DavidAttenborough or even with + or - to replace spaces without losing the structural integrity of react-router.

Božo Stojković
  • 2,893
  • 1
  • 27
  • 52
John107
  • 2,157
  • 3
  • 20
  • 36
  • 4
    you could do something like this: props.data.name.split(' ').join(''); Or use regex – floor Apr 06 '18 at 14:54
  • 1
    You could use .split(' ').join('-') on props.data.name, but I'm not sure if your router will break – Ron Nabuurs Apr 06 '18 at 14:55
  • 1
    @floor you beat me too it – Ron Nabuurs Apr 06 '18 at 14:55
  • Possible duplicate of [When to encode space to plus (+) or %20?](https://stackoverflow.com/questions/2678551/when-to-encode-space-to-plus-or-20) – Ruan Mendes Apr 06 '18 at 15:06
  • 1
    It's called a slug, you can do this with [slugify](https://www.npmjs.com/package/slugify) or [others](https://www.npmjs.com/search?q=slug). What do you mean by _losing the structural integrity of react-router_? – Gabriel Bleu Apr 06 '18 at 15:46

2 Answers2

2

You can use regex for Putting (- or +) in the url example

let name = props.data.name;
name = name.replace(/\s+/g, '-');
const url = `/lookup/${name}

<Link to={url}>{props.data.name}</Link>

you can either add + or -

  • on some browser this will change only the first occurance of %20, try to add a loop (while(name.contains("%20") ... replace) or a test to use replaceAll if supported – phoenixstudio Dec 15 '20 at 11:03
1

Actually, + is not valid as an encoding for spaces in the path, only in the query string. See When to encode space to plus (+) or %20? and https://github.com/ReactTraining/react-router/issues/2407

You cannot do what you are asking

Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217