1

I have a variable named siteURL which is set using window.location.href.

I'm wanting to trim off the the last 10 characters which in this case is ...index.html.

var siteURL = window.location.href;

if (siteURL.endsWith('index.html')) {
   siteURL.substring(0, siteURL.length - 10);
}

//log the output
console.log(siteURL);

I'm trying this but it doesn't seem to be removing the last 10 character. Does anyone know where I'm going wrong and could point me in the right direction?

Caleb Davenport
  • 613
  • 5
  • 18
finners
  • 875
  • 16
  • 31

3 Answers3

3

You need to store the returned value of String.substring() back in siteUrl variable. Note also that strings are inmutables on Javascript (Check next reference too: Are JavaScript strings immutable? Do I need a "string builder" in JavaScript?).

var siteURL = "some/url/with/index.html";

if (siteURL.endsWith('index.html'))
{
   siteURL = siteURL.substring(0, siteURL.length - 10);
}

console.log(siteURL);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

However, a better approach for what you want to is to use String.replace() with a regular expression:

var siteURL = "some/url/with-index.html/index.html";
siteURL = siteURL.replace(/index\.html$/, "");
console.log(siteURL);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
Shidersz
  • 16,846
  • 2
  • 23
  • 48
  • You're a legend. That's exactly what I was trying to do. Thanks for including the link to string replace. Super handy! – finners May 13 '19 at 16:01
1

You're performing the action, you just need to actually assign the value.

siteURL = siteURL.substring(0, siteURL.length - 10);

Caleb Davenport
  • 613
  • 5
  • 18
1

You can do:

var newStr = siteURL.substring(0, siteURL.length-10);

var newStr = siteURL.substr(0, siteURL.length-10);

var newStr = siteURL.slice(0, siteURL.length-10);

Any of them will work:

console.log(newStr);
Evik Ghazarian
  • 1,803
  • 1
  • 9
  • 24