4

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.

3
  • Your two code samples are not the same. The first yields "aaee" the second "eeaa"; Commented Aug 23, 2012 at 6:46
  • @Dave thats what I want to do, read the bold :P 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? Commented Aug 23, 2012 at 6:48

6 Answers 6

9

There's no built-in operator that allows you to achieve this as in the first example. Also test = "ee" + test; seems pretty self explanatory.

Sign up to request clarification or add additional context in comments.

Comments

4

You could do it this way ..

test = test.replace (/^/,'ee');

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


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

Comments

1

You have a few possibilities although not a really short one:

var test = "aa";

// all yield eeaa
result = "ee" + test;
result = test.replace(/^/, "ee");

Comments

0
var test = "aa";
 alert('ee'.concat(test));

1 Comment

isn't test = "ee" + test; shorter?
0

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.