my code:
var test = "aa";
test += "ee";
alert(test);
Prints out "aaee"
How can I do the same thing, but add the string not to end, but start: Like this:
var test = "aa";
test = "ee" + test;
This is the long way, but is there somekind of shorter way like in 1st example?
What I want is that I must not write the initial variable out again in definition.
my code:
var test = "aa";
test += "ee";
alert(test);
Prints out "aaee"
How can I do the same thing, but add the string not to end, but start: Like this:
var test = "aa";
test = "ee" + test;
This is the long way, but is there somekind of shorter way like in 1st example?
What I want is that I must not write the initial variable out again in definition.
Share Improve this question edited Aug 23, 2012 at 6:59 Jaanus asked Aug 23, 2012 at 6:43 JaanusJaanus 16.5k52 gold badges149 silver badges205 bronze badges 3- Your two code samples are not the same. The first yields "aaee" the second "eeaa"; – The Internet Commented Aug 23, 2012 at 6:46
- @Dave thats what I want to do, read the bold :P – Jaanus Commented Aug 23, 2012 at 6:47
- jQuery offers a .prepend() function. In pure JS I would just do test += "ee"; Also, why do you want to do this? – The Internet Commented Aug 23, 2012 at 6:48
6 Answers
Reset to default 9There's no built-in operator that allows you to achieve this as in the first example. Also test = "ee" + test;
seems pretty self explanatory.
You could do it this way ..
test = test.replace (/^/,'ee');
disclaimer: http://xkcd.com/208/
You have a few possibilities although not a really short one:
var test = "aa";
// all yield eeaa
result = "ee" + test;
result = test.replace(/^/, "ee");
var test = "aa";
alert('ee'.concat(test));
What you have, test = "ee" + test;
seems completely fine, and there's no shorter way to do this.
If you want a js
solution on this you can do something like,
test = test.replace(/^/, "ee");
There are a whole lot of ways you can achieve this, but test = "ee" + test;
seems the best imo.
You can add a string at the start (multiple times, if needed) until the resulting string reaches the length you want with String.prototype.padStart(). like this:
var test = "aa";
test = test.padStart(4, "e");
alert(test);
Prints out
eeaa
var test = "aa";
test = test.padStart(5, "e");
alert(test);
Prints out
eeeaa