Reputation: 275
i am using next js and i want to make human readble urls like the urls of stackoverflow questions for each of my webpages using "-" betwwen each words but i dont know how to do it corrently my url looks like this
localhost:3001/Morbius%OTT%release%date%confirmed%3F
i want to convert this in to this
localhost:3001/Morbius-OTT-release-date-confirmed-?
<div className="question11">
{data.map((itm) => (
<Link
key={itm._id}
href={{
pathname: "query/[itm]",
}}
as={`/${encodeURIComponent(itm.Name)}`}
>
<Alert className="question13">{itm.Name}</Alert>
</Link>
))}
</div>
Upvotes: 1
Views: 486
Reputation: 424
Replace the spaces with dashes before encoding the itm.name
:
encodeURIComponent("Morbius OTT release date confirmed ?".replace(/ /g, "-"))
// Output: Morbius-OTT-release-date-confirmed-%3F
Code:
<div className="question11">
{data.map((itm) => (
<Link
key={itm._id}
href={{
pathname: "query/[itm]",
}}
as={`query/${encodeURIComponent(itm.name.replace(/ /g, "-"))}`}
>
<Alert className="question13">{itm.Name}</Alert>
</Link>
))}
</div>
Remove special characters (except .
, -
, _
, .
, and ~
since they don't need to be encoded) if you don't want them encoded:
<Link
key={itm._id}
href={{
pathname: "query/[itm]",
}}
as={`/query/${encodeURIComponent(itm.name.replace(/[^a-zA-Z0-9 - _ . ~]/g, "").replace(/ /g, "-"))}`}
>
Upvotes: 1