What is the fastest method, to add a new value at the beginning of a string?
This question is related to
javascript
string
performance
concat
jsperf
ES6:
let after = 'something after';
let text = `before text ${after}`;
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}`;
You can use
var mystr = "Doe";
mystr = "John " + mystr;
console.log(mystr)
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
You could do it this way ..
var mystr = 'is my name.';_x000D_
mystr = mystr.replace (/^/,'John ');_x000D_
_x000D_
console.log(mystr);
_x000D_
disclaimer: http://xkcd.com/208/
EcmaScript 2017 added special functions to string prototype for that. padStart and padEnd are two new methods available in JavaScript string prototype object. As their name implies, they allow for formatting a string by adding padding characters at the start or the end. (Not supported by IE11 and lower)
var mystr = "Doe";
mystr = mystr.padStart('John ');
you could also do it this way
"".concat("x","y")
Another option would be to use join
var mystr = "Matayoshi";
mystr = ["Mariano", mystr].join(' ');
Source: Stackoverflow.com