0

I would like to strip the item name from a URL using Javascript. Not sure whether Regex is the way to go with this, as I need to capitalize the item name after it is extracted.

BEFORE https://www.sportsdirect.com/karrimor-lifestyle-fleece-mens-443326?colcode=44332603

AFTER "Karrimor Lifestyle Fleece Mens 443226"

So anything between the / after the URL and before the ? character and stripping out any - characters

Gracie
  • 896
  • 5
  • 14
  • 34

3 Answers3

0

Use new URL(url).pathname.substring(1) to get the pathname from your url. Then split it by -, map it to uppercase only the first characters of every word and finally join it back. Hope this is what you want :)

var url = 'https://www.sportsdirect.com/karrimor-lifestyle-fleece-mens-443326?colcode=44332603';
var expected_part = new URL(url).pathname.substring(1); // to ignore 1st character
var expected_result = expected_part.toLowerCase()
  .split('-')
  .map((s) => s.charAt(0).toUpperCase() + s.substring(1))
  .join(' ');
console.log(expected_result);
A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103
0

This should work:

var result = 'https://www.sportsdirect.com/karrimor-lifestyle-fleece-mens-443326?colcode=44332603'
  .replace(/(.*\/|\?.*)/g, '')
  .split(/\W/)
  .map(function(w) {
    return w[0].toUpperCase() + w.substr(1);
  })
  .join(' ');
  
console.log(result);

To give some explanation of what the snippet does (line by line):

  1. replace(/(.*\/|\?.*)/g, '') remove unwanted parts of URL via RegEx (but keep the path string as it is, with hyphens etc.)
  2. split(/\W/) split into parts along non-word characters (produces array)
  3. map(function(w) {... transform every array element...
  4. return w[0].toUpperCase() + w.substr(1); ... to have the first "letter" uppercased.
  5. .join(' '); ... and join the elements to a string again, delimited by a whitespace.
bkis
  • 2,530
  • 1
  • 17
  • 31
0

This is how I did it:

function capitalizeFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
}
var input = "https://www.sportsdirect.com/karrimor-lifestyle-fleece-mens-443326?colcode=44332603";
input = input.substring(0, input.indexOf("?"));
input = input.substring(input.lastIndexOf("/") + 1);
input = input.split("-").map(x => capitalizeFirstLetter(x)).join(" ");

capitalizeFirstLetter was taken from How do I make the first letter of a string uppercase in JavaScript?

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175