2

I'm trying to split this string

"http://localhost/webproject/products.html?product=Apple%20iPhone%206%20With%20FaceTime%20class="

to this

"Apple iphone 6 with Facetime"

but my code only splits it to

"Apple iphone 6 with Facetime class"

and when I'm trying to remove the class word and alert the string, it appears as empty. When I alert split5 it appears as NaN

var url = window.location.href;
var split = url.split('=');
var split2 = split[1];
var split3 = split2.replace(/20/g,"");
var split4 = split3.replace(/%/g, " ");
var split5 = split4.count-5;
var split6 = split4.slice(0, split5);
alert(split6);
4
  • 1
    split4.count? You mean split4.length? Commented May 18, 2015 at 18:56
  • Save yourself some time: var split2 = decodeURI(split[1]); Commented May 18, 2015 at 18:58
  • Dammit I forgot thank you. I'm used to the Array List in c#. Commented May 18, 2015 at 18:59
  • 1
    If product and class are meant to be separate arguments, there should be a & between them that you can .split() on first. Commented May 18, 2015 at 19:00

4 Answers 4

1

@Karim, what's going on is you're using replace and then counting the -5 over the location of those characters. That's why it is returning NaN.

Here is what you want:

var url = 'http://localhost/webproject/products.html?product=Apple%20iPhone%206%20With%20FaceTime%20class=';
var split = url.split('=');
var split2 = split[1];
var split3 = split2.split('%20');
alert(split3.join(' '));

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

Comments

0

You can done better way using decodeURI() method. Instead of count you have to use length.

string don't have count property that is why you are getting `NaN1.

var url = window.location.href;
var split = url.split('=');
var split2 = decodeURI(split[1]);
var split5 = split2.length-5;
var split6 = split2.substring(0, split5);
alert(split6);

Comments

0

Also, as a shortcut, you can set the second argument of the string.slice method to a negative number to remove that many characters from the end of the string, eg -5 to slice off the last 5 characters.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice

Comments

0

You can split your string by '%20', remove the last value using pop() and then join the result:

var url = "http://localhost/webproject/products.html?product=Apple%20iPhone%206%20With%20FaceTime%20class="

var split1 = url.split('=')[1]
var split2 = split1.split('%20')
split2.pop()
alert(split2.join(' '))

More info on Array.prototype.pop()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.