Mike
Mike

Reputation: 607

Javascript Replace Certain Characters of href after the last slash /

I have this a tag

<a id="Link" href="mysite.net/K&N abc 123.html">Link</a>

I need to use JavaScript to remove non alphanumeric characters then replace spaces with a dash - and lowercase the result.

So everything after /K&N abc 123.html and leave the rest of the href untouched.

The final result would look like this

<a id="Link" href="mysite.com/kn-abc-123.html">Link</a>

I have some code to start but not quite getting it put together right to give the correct result.

var str = document.getElementById("Link").getAttribute("href");
str = str.replace(/\W+/g, '-').toLowerCase();
document.getElementById('Link').setAttribute("href",str);

Upvotes: 0

Views: 1396

Answers (3)

Dustin Stiles
Dustin Stiles

Reputation: 1424

Here's a bin. https://jsbin.com/gojoseduji/3/edit?html,output

var href = document.getElementById("Link").getAttribute('href');
var str = href
  // replace each block of whitespace with a single '-' character
  .replace(/\s+/g, '-')
  // Filter out non alphanumerics, excluding : / -
  .replace(/[^\:\/\-\w\s.]+/g, "")
  // get rid of any hyphens that follow a slash
  .replace(/\/-/g, '/')
  .toLowerCase();

I just used the whitespace identifier, and make sure to make it global :)

EDIT: Added the condition to strip all non alpha-numerics except [/ - :]. I stripped the whitespace first and had the second regex ignore the hypens. I also made the variable names different, as your original code modified the variable. Just my preference.

EDIT-AGAINN: This original way was nice, but now there's a few different regEx's, maybe someone with smoother regex skills can condense those down and make a better answer?

Upvotes: 1

anubhava
anubhava

Reputation: 786031

You can use replace with a callback:

var href = document.getElementById("Link").getAttribute('href');

href = href.replace(/^((?:.*?\/{2})?[^\/]*\/)(.+)$/, function($0, $1, $2) {
      return $1 + $2.replace(/[^\w\s.]+/g, '').replace(/\s+/g, '-').toLowerCase(); });

document.getElementById('Link').setAttribute("href", href);
//=> mysite.net/kn-abc-123.html

Or with ftp:// in URL:

str = 'ftp://mysite.net/K&N abc 123.html'

str = str.replace(/^((?:.*?\/{2})?[^\/]*\/)(.+)$/, function($0, $1, $2) {
      return $1 + $2.replace(/[^\w\s.]+/g, '').replace(/\s+/g, '-').toLowerCase(); });

//=> ftp://mysite.net/kn-abc-123.html

Upvotes: 0

gurvinder372
gurvinder372

Reputation: 68433

try this

var str = document.getElementById("Link").getAttribute("href");

var lastitem = str.split("/").pop(); //taking out last item after slash 

lastitem = lastitem.split( " " ).map( function(value){ return value.replace(/[*\(\)&/]/g, '').toLowerCase() } ).join( "-" );    //removing special characters and replacing space with hyphen

str = str.substring(0, str.lastIndexOf("/")) + lastitem;

document.getElementById('Link').setAttribute("href",str);

Upvotes: 0

Related Questions