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>

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Doh! Thanks very much for this - On that note I think its time to get some shut-eye!
@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.
Thanks for the tip gdoron, I'll be sure to use jsLint in future. I'll also simplify (''.+urlPath1+'') as described. Take care!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.