What is the fastest method, to add a new value at the beginning of a string?
Asked
Active
Viewed 2.4e+01k times
166
9 Answers
318
var mystr = "Doe";
mystr = "John " + mystr;
Wouldn't this work for you?

T J
- 42,762
- 13
- 83
- 138

Thor Jacobsen
- 8,621
- 2
- 27
- 26
-
1Wait wouldn't using += work as well or would it add it to the end – Aug 27 '19 at 10:04
-
6@JuicY_Burrito `+=` Appends to the end of the text. – Mark Kramer Nov 26 '19 at 20:29
171
You could do it this way ..
var mystr = 'is my name.';
mystr = mystr.replace (/^/,'John ');
console.log(mystr);
disclaimer: http://xkcd.com/208/

Gabriele Petrioli
- 191,379
- 34
- 261
- 317
-
30I am tempted to upvote this for the xkcd strip. Great stuff! Your elegant solution is most probably slower because it instantiates the regular expressions processor. – Rolf Nov 10 '17 at 00:40
-
23@Rolf not most probably. It is **certainly** slower than the `prestring + 'original string';` solution. – Gabriele Petrioli Nov 10 '17 at 07:17
-
3@GabrielePetrioli The advantage is that you can just add to your dot chain ( pipeline ). You can even append something, like so mystr.replace (/$/,' by Gabriele'). It might be slower but it's exactly what I was looking for. – Mateja Petrovic Aug 09 '18 at 00:23
-
1Not to worry. https://jsperf.com/prepend-text-to-string/5 It is just around 50-100 times slower than simple string+string. But you still can use your regular expression skills. That outweighs the slowdown, right? – metalim Apr 22 '19 at 11:29
82
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

KyleMit
- 30,350
- 66
- 462
- 664
-
1Since we want to test *prepend*, and not just concatenate, I've updated the tests: https://jsperf.com/prepend-text-to-string/5 – metalim Apr 22 '19 at 11:32
-
@metalim, were there any material changes of note that you made to the tests? A prepend is just the ordered half of string concatenation. Also, for jsPerf, you don't need to throw the test cases in a loop; jsPerf call each method thousands of times to get a baseline of scores. Perf tests optimize particular scenarios, and I'm not sure how common it prepend a the same string 1,000 times. – KyleMit Apr 22 '19 at 18:08
-
There can be significant difference if you append short string to long, or long string to short. Since we're interested in *prepending* short string to arbitrary string, that is what is done in tests: prepending short string to increasing longer string. Loops are there to test 1000 different lengths of the suffix string, to avoid testing just short or just long. @KyleMit, if you have better idea, feel free to implement it in next test iteration. – metalim Apr 23 '19 at 08:38
17
ES6:
let after = 'something after';
let text = `before text ${after}`;

Griffi
- 243
- 2
- 9
-
11While this code snippet may solve the question, [including an explanation](//meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, this reduces the readability of both the code and the explanations! – kayess Dec 20 '16 at 14:41
-
2
8
you could also do it this way
"".concat("x","y")

hjpotter92
- 78,589
- 36
- 144
- 183

chirag
- 91
- 1
- 1
-
3and why not "x".concat("y")? Just to add another string instantiation and make it slower? – metalim Apr 22 '19 at 11:31
7
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}`;

Boris Verkhovskiy
- 14,854
- 11
- 100
- 103

Ilan Schemoul
- 1,461
- 12
- 17
2
Another option would be to use join
var mystr = "Matayoshi";
mystr = ["Mariano", mystr].join(' ');

MatayoshiMariano
- 2,026
- 19
- 23
1
You can use padStart like this:
'ello'.padStart(5,'h');
//padStart(maxLength, fillString)
//output: hello

som
- 2,023
- 30
- 37

Mustafa Yasin
- 11
- 2
-
1Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 27 '22 at 07:12
-
This is actually a nice (functional) answer ... e.g. it allows you to do `a = b?.padStart(b.length + 1, '/')` ... which is equivalent (i think) to the less composable ```a = b && `/${b}` ``` – som Aug 27 '22 at 02:27