Question

I need to parse querystrings that contain both text and numbers. For example the following querystring:

?userID=12&team=Sales&quarter=Q1&count=2310

should be translated into the following JavaScript object:

{
userID:12, // not "12"
team:"Sales",
quarter:"Q1",
count:2310 // not "2310"
}

Currently I am doing it in two steps:

  1. Parse the querystring
  2. Go through all the parameters and identify which ones are numbers (either with a regex or an isNumber function !isNaN(parseFloat(n)) && isFinite(n)

This seems rather inefficient especially as most of my parameters are not numbers. Is there a better way?

Was it helpful?

Solution

do you know where are you going to use the specify value?

Because if you multiplying any string in number format like "3239" by 1 this will convert that string in number..

var example = 5 + (o.count*1) //o.count will be a number...

OTHER TIPS

Two suggestions:

  1. If you know which parameters are going to hold numbers, only do the conversion for those
  2. The fastest way to convert strings to numbers as far as I know is to use the unary operator on them, as follows:

    +(strVar)

Also multiplying by 1 is supposed to be fast AFAIK

After you parse the querystring you can convert those string representations of integer value to an actual integer like this:

var obj; // your object that the string is parsed into, with all values as strings.
for (var prop in obj) {
    if (String(parseInt(obj[prop])) === obj[prop]) {
        obj[prop] = parseInt(obj[prop]);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top