Prepend text to beginning of string
Asked Answered
R

9

170

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

Rheotaxis answered 23/5, 2011 at 7:27 Comment(0)
G
327
var mystr = "Doe";
mystr = "John " + mystr;

Wouldn't this work for you?

Gagger answered 23/5, 2011 at 7:30 Comment(2)
Wait wouldn't using += work as well or would it add it to the endCapone
@JuicY_Burrito += Appends to the end of the text.Sokoto
I
174

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.

Intertwist answered 23/5, 2011 at 7:32 Comment(4)
I 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.Anlace
@Anlace not most probably. It is certainly slower than the prestring + 'original string'; solution.Intertwist
@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.Ilysa
Not to worry. 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?Hubby
D
91

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

Does answered 29/3, 2019 at 1:4 Comment(3)
Since we want to test prepend, and not just concatenate, I've updated the tests: jsperf.com/prepend-text-to-string/5Hubby
@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.Does
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.Hubby
B
18

ES6:

let after = 'something after';
let text = `before text ${after}`;
Bs answered 20/12, 2016 at 14:12 Comment(2)
While this code snippet may solve the question, including an explanation 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!Jae
ES6: String InterpolationPropitious
S
8

you could also do it this way

"".concat("x","y")
Syconium answered 15/8, 2016 at 11:15 Comment(1)
and why not "x".concat("y")? Just to add another string instantiation and make it slower?Hubby
V
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}`;
Vorticella answered 16/11, 2016 at 17:1 Comment(1)
This is technically correct, but OP asked for a way to prepend text to beginning of string, not the end of it. Although, yes, you can put it anywhere with ES6 template strings.Upcast
B
3

Another option would be to use join

var mystr = "Matayoshi";
mystr = ["Mariano", mystr].join(' ');
Bellhop answered 12/9, 2018 at 14:25 Comment(0)
W
2

You can use padStart like this:

'ello'.padStart(5,'h');
//padStart(maxLength, fillString)
//output: hello

See MDN: String.prototype.padStart()

Wattenberg answered 26/5, 2022 at 21:45 Comment(2)
Your 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.Someway
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}` Gynaeco
P
0

You can use

var mystr = "Doe";
mystr = "John " + mystr;
console.log(mystr)
Pistachio answered 23/5, 2011 at 7:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.