Domanda

Qual è il metodo più veloce, aggiungere un nuovo valore all'inizio di una stringa?

È stato utile?

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/

.
.

Aspetta, ho dimenticato di sfuggire a uno spazio. Wheeeeeee [taptaptap] eeeeee.

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

https://jsperf.com/prepend-text-to-String/1

 Inserisci Descrizione dell'immagine qui

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
scroll top