什么是最快的方法,在字符串开头添加一个新值?

有帮助吗?

解决方案

var mystr = "Doe";
mystr = "John " + mystr;
.

这不是你的工作吗?

其他提示

你可以这样做..

var mystr = 'is my name.';
mystr = mystr.replace (/^/,'John ');

console.log(mystr);
.

免责声明: http://xkcd.com/208/


自问题是关于什么是最快的方法,我想我会呕吐添加一些perf指标。

tl; dr 赢家,通过宽边缘,是+运算符,永远不要使用正则表达式

https://jsperf.com/prepene-text-to-string/1

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)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top