Prepend text to beginning of string

JavascriptStringPerformanceConcatJsperf

Javascript Problem Overview


What is the fastest method, to add a new value at the beginning of a string?

Javascript Solutions


Solution 1 - Javascript

var mystr = "Doe";
mystr = "John " + mystr;

Wouldn't this work for you?

Solution 2 - Javascript

You could do it this way ..

var mystr = 'is my name.';
mystr = mystr.replace (/^/,'John ');

console.log(mystr);

disclaimer: http://xkcd.com/208/


![Wait, forgot to escape a space. Wheeeeee[taptaptap]eeeeee.][1]

[1]: http://i.stack.imgur.com/zFmVi.png "Wait, forgot to escape a space. Wheeeeee[taptaptap]eeeeee."

Solution 3 - Javascript

Since the question is about what is the fastest method, I thought I'd throw up add some perf metrics.

TL;DR The winner, by a wide margin, is the + operator, and please never use regex

https://jsperf.com/prepend-text-to-string/1

enter image description here

Solution 4 - Javascript

ES6:

let after = 'something after';
let text = `before text ${after}`;

Solution 5 - Javascript

you could also do it this way

"".concat("x","y")

Solution 6 - Javascript

If you want to use the version of Javascript called ES 2015 (aka ES6) or later, you can use template strings introduced by ES 2015 and recommended by some guidelines (like Airbnb's style guide):

const after = "test";
const mystr = `This is: ${after}`;

Solution 7 - Javascript

Another option would be to use join

var mystr = "Matayoshi";
mystr = ["Mariano", mystr].join(' ');

Solution 8 - Javascript

You can use

var mystr = "Doe";
mystr = "John " + mystr;
console.log(mystr)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionmate64View Question on Stackoverflow
Solution 1 - JavascriptThor JacobsenView Answer on Stackoverflow
Solution 2 - JavascriptGabriele PetrioliView Answer on Stackoverflow
Solution 3 - JavascriptKyleMitView Answer on Stackoverflow
Solution 4 - JavascriptGriffiView Answer on Stackoverflow
Solution 5 - JavascriptchiragView Answer on Stackoverflow
Solution 6 - JavascriptIlan SchemoulView Answer on Stackoverflow
Solution 7 - JavascriptMatayoshiMarianoView Answer on Stackoverflow
Solution 8 - JavascriptMayankView Answer on Stackoverflow