Anteponga il testo all'inizio della stringa
-
09-09-2020 - |
Domanda
Qual è il metodo più veloce, aggiungere un nuovo valore all'inizio di una stringa?
Soluzione
var mystr = "Doe";
mystr = "John " + mystr;
.
Non funzionerebbe questo per te?
Altri suggerimenti
Potresti farlo in questo modo ..
var mystr = 'is my name.';
mystr = mystr.replace (/^/,'John ');
console.log(mystr);
.
Disclaimer: http://xkcd.com/208/
..
Poiché la domanda riguarda qual è il metodo più veloce , ho pensato che avrei vomitato aggiungere alcune metriche di perf.
TL; DR Il vincitore, da un ampio margine, è l'operatore +
e per favore non utilizzare mai regex
ES6:
let after = 'something after';
let text = `before text ${after}`;
you could also do it this way
"".concat("x","y")
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}`;
Another option would be to use join
var mystr = "Matayoshi";
mystr = ["Mariano", mystr].join(' ');
You can use
var mystr = "Doe";
mystr = "John " + mystr;
console.log(mystr)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow