Prepend text to beginning of string

不想你离开。 提交于 2019-11-26 17:39:35

问题


What is the fastest method, to add a new value at the beginning of a string?


回答1:


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

Wouldn't this work for you?




回答2:


You could do it this way ..

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

console.log(mystr);

disclaimer: http://xkcd.com/208/





回答3:


ES6:

let after = 'something after';
let text = `before text ${after}`;



回答4:


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




回答5:


you could also do it this way

"".concat("x","y")



回答6:


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}`;



回答7:


Another option would be to use join

var mystr = "Matayoshi";
mystr = ["Mariano", mystr].join(' ');



回答8:


You can use

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


来源:https://stackoverflow.com/questions/6094117/prepend-text-to-beginning-of-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!