What is the fastest method, to add a new value at the beginning of a string?
Thor Jacobsen
var mystr = "Doe";
mystr = "John " + mystr;
Wouldn't this work for you?
You could do it this way ..
var mystr = 'is my name.';
mystr = mystr.replace (/^/,'John ');
console.log(mystr);
disclaimer: http://xkcd.com/208/
ES6:
let after = 'something after';
let text = `before text ${after}`;
chirag
you could also do it this way
"".concat("x","y")
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
If you want to use the new version of Javascript called ES 2015 (aka ES6), you could use Template strings introduced by ES 2015 and thus recommended by some guidelines (as airbnb's one) :
const after = `This is : ${after}`;
Another option would be to use join
var mystr = "Matayoshi";
mystr = ["Mariano", mystr].join(' ');
Mayank
You can use
var mystr = "Doe";
mystr = "John " + mystr;
console.log(mystr)
来源:https://stackoverflow.com/questions/6094117/prepend-text-to-beginning-of-string