2

Suppose I have this URL:

www.example.com/product-p/xxx.htm

The following javascript code picks out the phrase product-p from the URL:

urlPath = window.location.pathname; 
urlPathArray = urlPath.split('/'); 
urlPath1 = urlPathArray[urlPathArray.length - 2];

I can then use document.write to display the phrase product-p:

document.write(''+urlPath1+'')

My question is...

How do I create an IF statement such that if urlPath1 = 'product-p' then document.write (something), else document.write (blank)?

I have tried to do this but my syntax is probably wrong (I'm not too good at JS).

I initially thought the code would be this:

<script type="text/javascript"> 
urlPath=window.location.pathname; 
urlPathArray = urlPath.split('/'); 
urlPath1 = urlPathArray[urlPathArray.length - 2]; 

if (urlPath1 = "product-p"){
    document.write('test'); 
}
else {
    document.write(''); 
}
</script>
gdoron
  • 147,333
  • 58
  • 291
  • 367
ghilton
  • 127
  • 1
  • 3
  • 12

1 Answers1

5
if (urlPath1 = "product-p")
//           ^ single = is assignment

    Should be:

if (urlPath1 == "product-p")
//           ^ double == is comparison

Note that:

document.write(''+urlPath1+'')

Should be simply:

document.write(urlPath1)

You're concating the urlpath string with two empty strings... it doesn't do much.

gdoron
  • 147,333
  • 58
  • 291
  • 367
  • Doh! Thanks very much for this - On that note I think its time to get some shut-eye! – ghilton Jul 02 '12 at 23:01
  • @user1438551. Don't worry things like that happens. Had you tested your code with jsLint it would have told you that mistake. Good night warrior. – gdoron Jul 02 '12 at 23:16
  • Thanks for the tip gdoron, I'll be sure to use jsLint in future. I'll also simplify (''.+urlPath1+'') as described. Take care! – ghilton Jul 03 '12 at 10:49