Malyo
Malyo

Reputation: 2000

Move n characters from front of string to the end

It seems like an easy problem, but i can't find solution. I want to take first, let's say 2 letters from string, and move them to the end of this string. So for example, OK12 would become 12OK.

edit: So far i've tried cutting string off, then adding it to the rest of the string, but i tought there's a one-line solution for that, like predefined function or something.

Upvotes: 14

Views: 26704

Answers (4)

Phrogz
Phrogz

Reputation: 303215

Various techniques:

str.slice(2) + str.slice(0,2);

str = str.replace(/^(.{2})(.+)/, '$2$1');

for (var a=str.split(""),i=2;i--;) a.push(a.shift());
str = a.join('');

Upvotes: 8

Marius Balčytis
Marius Balčytis

Reputation: 2651

text.slice(2) + text.slice(0, 2);

Upvotes: 1

gdoron
gdoron

Reputation: 150253

"OK12".substr(2) + "OK12".substr(0,2)

Generic solution:

var result = str.substr(num) + str.substr(0, num);

Live DEMO

Upvotes: 18

Mert Emir
Mert Emir

Reputation: 691

var a='ok12';
a=a.substr(2,a.length-2)+a.substr(0,2);

Upvotes: 1

Related Questions