0

I'm trying to redirect from www.domain1.com to www.domain2.com getting the actual domain name.

Let's say that our page is www.domain1.com:

  var domainName = window.location.host;
  var domainNumber =  domainName.substr(10, 1);
  var finalDomain = (domainNumber+1);

If I print finalDomain on the screen, I got 11. So because of that my redirect is not working. How do I do domainNumber plus 1, so I got 2 and not 11?

4 Answers4

0

substr method will return you a string, not a number. so you are getting "1" , not 1

when you do "1"+1, you will get "11"

use parseInt() method to convert "1" to 1 before the addition operation.

var finalDomain = parseInt(domainNumber)+1;
Shyju
  • 214,206
  • 104
  • 411
  • 497
0

This function should do the trick parseInt:

Converts a string to an integer.

var finalDomain = parseInt(domainNumber) + 1;

The issue you are having is because in javascript "1" + 1 is "11". So, you need to convert the string "1" to int in order to add it 1 afterwards.

Test it yourself here:

alert("1" + 1 === "11")

alert(1 + 1 === 2)
Cacho Santa
  • 6,846
  • 6
  • 41
  • 73
0

domainNumber is a string, not a number, so when you add 1, you're actually concatenating the string "1" onto the end of a string "1" to make "11". You need to convert it into a number using the parseInt() function, as follows:

var domainNumber = parseInt(domainName.substr(10, 1), 10);

Note: The second parameter passed to parseInt() signifies that the string is in decimal (base 10). Now domainNumber is a number rather than a string, so if you try to add one to it you'll get 2.

var finalDomain will be a number, unless you set it to be a string by calling toString():

var finalDomain = (domainNumber + 1).toString() - If you do this, finalDomain will be a string containing the value "2".

Hope this helps.

-1

try this

var domainName = window.location.host;
var domainNumber =  domainName.substr(10, 1);
domainNumber = parseInt(domainNumber);
var finalDomain = (domainNumber+1);

u need to parse ur domainNumber variable to integer type in order to do addition. see here http://www.w3schools.com/jsref/jsref_parseint.asp

Tommy Lee
  • 794
  • 2
  • 11
  • 30