How To Convert a User Input to URL-Friendly String

Hey all,

I spent a few minutes on this earlier and wanted to share in case anyone had a similar use case. It’s not uncommon to create a URL based on user input (example.com/company-name) but you never know what someone is going to put in that input field— that’s why we have to do some work to make it url-friendly.

This function turns spaces into hyphens, removes whitespace & leading/trailing hyphens, removes illegal characters, & limits to 32 characters.

const sanitizeForUrl = (input) =>
  input
    .replace(/\s+/g, '-')
    .replace(/[^a-zA-Z0-9-]/g, '')
    .replace(/-+/g, '-')
    .replace(/^-+|-+$/g, '')
	.toLowerCase()
	.slice(0, 32);

const companyUrl = sanitizeForUrl(
  variables['f5a797d0-d19f-4252-941e-d8b6a66a8399-value']
)
return companyUrl


Hope someone finds this useful!

Note: I didn’t look too hard to see if there was built-in functionality for this— apologies if this is already possible without custom JS.

2 Likes

Awesome function @jasonvanguard :clap:

I took the liberty to add this to our roadmap. We’ll make a nocode formula out of this :raised_hands:

1 Like