How to Build/Concatenate Strings in JavaScript

How to build/concatenate strings in JavaScript?

With ES6, you can use

  • Template strings:

    var username = 'craig';
    console.log(`hello ${username}`);

ES5 and below:

  • use the + operator

    var username = 'craig';
    var joined = 'hello ' + username;
  • String's concat(..)

    var username = 'craig';
    var joined = 'hello '.concat(username);

Alternatively, use Array methods:

  • join(..):

    var username = 'craig';
    var joined = ['hello', username].join(' ');
  • Or even fancier, reduce(..) combined with any of the above:

    var a = ['hello', 'world', 'and', 'the', 'milky', 'way'];
    var b = a.reduce(function(pre, next) {
    return pre + ' ' + next;
    });
    console.log(b); // hello world and the milky way

Most efficient way to concat strings in javascript

Don't know if it's the fastest way, but what I find most readable (i.e. optimized for human eyes) is:

var str1 = "Hello ";
var str2 = "world!";
var res = [str1, str2].join('');
// output : "Hello world!"

Although usually only when we don't know ahead of time exactly what is going to be concatenated, so the sample looks really contrived.

Most efficient way to concatenate strings in JavaScript?

Seems based on benchmarks at JSPerf that using += is the fastest method, though not necessarily in every browser.

For building strings in the DOM, it seems to be better to concatenate the string first and then add to the DOM, rather then iteratively add it to the dom. You should benchmark your own case though.

(Thanks @zAlbee for correction)

Concatenate string through for loop

Don't declare a new str variable inside the loop with var str. Reuse the one you declare outside the loop. Also do +=

var divLength = $('div').length;

var str = '';
for(var i = 0; i < divLength; i++) {
str += "Div #" + i + ", ";
console.log(str);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
<div></div>
<div></div>
<div></div>

How do I concatenate a string with a variable?

Your code is correct. Perhaps your problem is that you are not passing an ID to the AddBorder function, or that an element with that ID does not exist. Or you might be running your function before the element in question is accessible through the browser's DOM.

Since ECMAScript 2015, you can also use template literals (aka template strings):

document.getElementById(`horseThumb_${id}`).className = "hand positionLeft";

To identify the first case or determine the cause of the second case, add these as the first lines inside the function:

alert('ID number: ' + id);
alert('Return value of gEBI: ' + document.getElementById('horseThumb_' + id));

That will open pop-up windows each time the function is called, with the value of id and the return value of document.getElementById. If you get undefined for the ID number pop-up, you are not passing an argument to the function. If the ID does not exist, you would get your (incorrect?) ID number in the first pop-up but get null in the second.

The third case would happen if your web page looks like this, trying to run AddBorder while the page is still loading:

<head>
<title>My Web Page</title>
<script>
function AddBorder(id) {
...
}
AddBorder(42); // Won't work; the page hasn't completely loaded yet!
</script>
</head>

To fix this, put all the code that uses AddBorder inside an onload event handler:

// Can only have one of these per page
window.onload = function() {
...
AddBorder(42);
...
}

// Or can have any number of these on a page
function doWhatever() {
...
AddBorder(42);
...
}

if(window.addEventListener) window.addEventListener('load', doWhatever, false);
else window.attachEvent('onload', doWhatever);

How to create a function that will concatenate any given string with second parameter?

It's because you're not returning anything in your function and you're not assigning it to your variable. Actually, str is in the scope of concOperator function.

A way to fix this:

let evalString = '';
let displayString = '';
let currentNumber = '5';

function concOperator(str, operator) {
return `${str} ${currentNumber} ${operator} `;
}

evalString = concOperator(evalString, '*');
displayString = concOperator(displayString, 'x');


Related Topics



Leave a reply



Submit