0

in php, i do this to connect strings

(pseudo code)

$myString = "";
for($i = 0;$i < 10;$i++)
    $myString .= $i;
echo $myString;

would give me 0123456789

you got the idea ,now, how can i do the same in javascript?

2
  • JS string concatenate symbol is a + Commented Jul 6, 2012 at 10:10
  • Is that an answer Shehzad? you accidentally put it in the comments box Commented Jul 6, 2012 at 10:11

4 Answers 4

3
var myString = "";
for(var i = 0;i < 10;i++)
    myString += i;
alert(myString);
Sign up to request clarification or add additional context in comments.

Comments

3

You should use the += operator.

So in pseudo code your code should be something like

myString = "";
for(i = 0;i < 10;i++)
    myString += i;
alert(myString);

Comments

2

Javascript uses the plus sign for string concatenation. So:

mystring = 'this' + 'that';   //gives string value "thisthat"

It is important to note that Javascript also uses the plus sign for numeric addition. This means that you can get into trouble with variable types.

var myInt = 5;
var myString = "5";

alert(myInt + 5);     //gives the string value "55".
alert(myString + 5);  //gives the integer value 10.

This means that your PHP trick of adding numbers together to make string, as per your question, will only work if you start with a string variable. PHP can recognise for itself that you intend it to be a string operation because of the concat operator; Javascript doesn't have that ability, so you have to tell it explicity by making sure that your variables are of the correct type.

Comments

1

Here it will do it.

var $myString = "";
    for(var $i = 0;$i < 10;$i++){
        $myString += $i;//+=  the equivalent of .= in JS
}
    alert( $myString );

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.