开发者

Prepend text to beginning of string

开发者 https://www.devze.com 2023-03-07 13:25 出处:网络
What开发者_Python百科 is the fastest method, to add a new value at the beginning of a string?var mystr = \"Doe\";

What开发者_Python百科 is the fastest method, to add a new value at the beginning of a string?


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/


Prepend text to beginning of string


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

Prepend text to beginning of string


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 padStart like this:

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

See MDN: String.prototype.padStart()


You can use

var mystr = "Doe";
mystr = "John " + mystr;
console.log(mystr)
0

精彩评论

暂无评论...
验证码 换一张
取 消