Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prepend text to beginning of string

People also ask

How do I put text at the beginning of a string?

Use the addition (+) operator to add a string to the beginning and end of another string, e.g. "before" + str + "after" . When used with strings, the addition operator concatenates the strings and returns the result.

How do I add to the beginning of a string in PHP?

Answer: Use the PHP Concatenation Operator There is no specific function to prepend a string in PHP. But you can use the PHP concatenation operator ( . ) to prepened a string with another string.

How do you concatenate strings in JavaScript?

The + Operator The same + operator you use for adding two numbers can be used to concatenate two strings. You can also use += , where a += b is a shorthand for a = a + b . If the left hand side of the + operator is a string, JavaScript will coerce the right hand side to 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/


Wait, forgot to escape a space.  Wheeeeee[taptaptap]eeeeee.


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

enter image description here


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(' ');