0

I have to inputs, one is for when you enter the a site name and the other one is only a readable input where the site name turns into the url. Like in the screenshot below:

enter image description here

So I have this:

  const handleChange = (e) => {    
    setSiteInfoDataAction({
      ...siteInfoData,
      siteName: e.target.value, // for the Site Name input
      url: e.target.value.toLowerCase().replace(/\s/g, "-"), // for the URL input
    });

    e.preventDefault();
  };

So the only validation i am doing is that every time there is a space, a hyphen is replacing the space. But I need to validate that the user is entering a valid name to recreate the URL. Get it? I need to regex to allow the user to enter only URL friendly characters.

Any ideas on how I can achieve that?

EDIT You should notice that the regex should validate only the part after the slash /. Just like in the input in the screenshot. So the regex won't validate any http/s or www. Just whatever is after the / should be URL friendly.

Non
  • 8,409
  • 20
  • 71
  • 123
  • This help: https://stackoverflow.com/questions/206059/php-validation-regex-for-url? – dale landry Jun 02 '20 at 07:07
  • Hi @dalelandry see what I posted on the EDIT section of my post. I need the regex to validate only what I have after the `/`. And replace the the regular site name for the URL if the regex matches what the user is typing in the site name field. – Non Jun 02 '20 at 07:10
  • @Non .. so can you modify something in the question that dale mentioned, so that it suits your needs? And if it's not working then add what you have tried to your question. – Bryan Jun 02 '20 at 07:49
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent – Drew Reese Jun 02 '20 at 08:09

1 Answers1

1

There are two ways to achieve your goal:
1. slugify the input
2. use built-in encodeURI() method

Both result in valid URL. However, the question specification (like replace ' ' with -) has closer match to slug conversion.

Slugify URL

Other than whitespaces, additional characters need to be handled, e.g:

  • special characters
  • non-word characters
  • other formatting

In JS, a function to slugify string can be created like this (Source):

function slugify(string) {
  const a = 'àáâäæãåāăąçćčđďèéêëēėęěğǵḧîïíīįìłḿñńǹňôöòóœøōõőṕŕřßśšşșťțûüùúūǘůűųẃẍÿýžźż·/_,:;'
  const b = 'aaaaaaaaaacccddeeeeeeeegghiiiiiilmnnnnoooooooooprrsssssttuuuuuuuuuwxyyzzz------'
  const p = new RegExp(a.split('').join('|'), 'g')

  return string.toString().toLowerCase()
    .replace(/\s+/g, '-') // Replace spaces with -
    .replace(p, c => b.charAt(a.indexOf(c))) // Replace special characters
    .replace(/&/g, '-and-') // Replace & with 'and'
    .replace(/[^\w\-]+/g, '') // Remove all non-word characters
    .replace(/\-\-+/g, '-') // Replace multiple - with single -
    .replace(/^-+/, '') // Trim - from start of text
    .replace(/-+$/, '') // Trim - from end of text
}

Then, in the code, call the slugify function

... //other codes
  url: slugify(e.target.value)
... //other codes

URL Encoding

This approach simply converts input characters to URL-encoded characters. encodeURI(string) is built-in JS function to handle it. Just call it in the function:

... //other codes
  url: encodeURI(e.target.value)
... //other codes

The drawback is the URL probably will not look pretty, although still valid.


The best choice depends on the use case. If URL for blog or article is desired, first approach would be the best. If it is used solely for converting plain text to valid URL, second approach would be faster.

yogski
  • 181
  • 1
  • 10
  • This is not working as I expect; I still can see the special characters in the URL field: https://monosnap.com/file/W646fTcFThOtAc9xKyQ86GBll6gffA – Non Jun 02 '20 at 16:24
  • What I am expecting is that those characters not URL friendly gets removed on the fly while the user is typing so i can show them an error message. – Non Jun 02 '20 at 16:25