Javascript 将文本添加到字符串的开头
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6094117/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Prepend text to beginning of string
提问by mate64
What is the fastest method, to add a new value at the beginning of a string?
在字符串的开头添加新值的最快方法是什么?
回答by Thor Jacobsen
var mystr = "Doe";
mystr = "John " + mystr;
Wouldn't this work for you?
这不适合你吗?
回答by Gabriele Petrioli
You could do it this way ..
你可以这样做..
var mystr = 'is my name.';
mystr = mystr.replace (/^/,'John ');
console.log(mystr);
disclaimer: http://xkcd.com/208/
免责声明:http: //xkcd.com/208/
回答by KyleMit
Since the question is about what is the fastestmethod, I thought I'd throw up add some perf metrics.
由于问题是关于最快的方法是什么,我想我会抛出添加一些性能指标。
TL;DRThe winner, by a wide margin, is the +
operator, and pleasenever use regex
TL;DR赢家,以较大的优势,是+
运营商,请永远不要使用正则表达式
https://jsperf.com/prepend-text-to-string/1
回答by Griffi
ES6:
ES6:
let after = 'something after';
let text = `before text ${after}`;
回答by chirag
you could also do it this way
你也可以这样做
"".concat("x","y")
回答by Ilan Schemoul
If you want to use the version of Javascript called ES 2015 (aka ES6) or later, you can use template stringsintroduced by ES 2015 and recommended by some guidelines (like Airbnb's style guide):
如果您想使用名为 ES 2015(又名 ES6)或更高版本的 Javascript,您可以使用ES 2015 引入的模板字符串,并由一些指南(如Airbnb 的样式指南)推荐:
const after = "test";
const mystr = `This is: ${after}`;
回答by MatayoshiMariano
回答by Mayank
You can use
您可以使用
var mystr = "Doe";
mystr = "John " + mystr;
console.log(mystr)