最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to concatenate variables in javascript? - Stack Overflow

programmeradmin0浏览0评论

I am trying to concatenate variables in inside a function and then return. In php we just put a period before the "=" but it is not working in javascript.

Can someone please help me figure this one out?

function NewMenuItem(){
    var output = "<input type='checkbox'> ";
    var output .= "<input type='text'> ";

    return output;
}

I am trying to concatenate variables in inside a function and then return. In php we just put a period before the "=" but it is not working in javascript.

Can someone please help me figure this one out?

function NewMenuItem(){
    var output = "<input type='checkbox'> ";
    var output .= "<input type='text'> ";

    return output;
}
Share Improve this question edited Sep 12, 2014 at 19:24 Dave Newton 160k27 gold badges260 silver badges307 bronze badges asked Sep 12, 2014 at 19:22 eldan221eldan221 691 gold badge2 silver badges5 bronze badges 6
  • 2 use the + operator: "some string" + "some other string", Expressions and Operators – Patrick Evans Commented Sep 12, 2014 at 19:23
  • . is the PHP concat operator. JS uses +. – Marc B Commented Sep 12, 2014 at 19:23
  • 3 google./search?q=javascript%20string%20concatenation – Felix Kling Commented Sep 12, 2014 at 19:23
  • You can also do output += "some more stuff" – Matt Burland Commented Sep 12, 2014 at 19:24
  • 2 You'll benefit from giving the MDN introduction to JavaScript a read-through. Especially if you already know another language, read through it so you know the syntax differences. – Mike 'Pomax' Kamermans Commented Sep 12, 2014 at 19:24
 |  Show 1 more ment

3 Answers 3

Reset to default 3

The + operator will concatenate two strings, ie. "Hello" + " World" //> "Hello World". Using += is a short cut for assigning and concatenating a variable with its self.

ie. instead of:

var myVar = "somestring";
myVar = myVar + "another String";

you can just do:

var myVar = "somestring";
myVar += "another String";

For your problem:

function NewMenuItem() {
    //This is just a small example. The end result is more broader then this
    var output = "<input type='checkbox'> ";
    output += "<input type='text'> ";
    return output;
} //end of NewMenuItem(){

"+=" is the standard way to concatenate in javascript;

var a = "yourname";
var b = "yourlastname";
var name = a + b;
var plete_name = "my name is: ";
plete_name += name;

result : my name is: yourname yourlastname

With Concat function or with plus operator (+).

Check this link jsfiddle to see a working example.

发布评论

评论列表(0)

  1. 暂无评论