javascript 将 n 个字符从字符串的前面移动到末尾

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10841868/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 11:12:59  来源:igfitidea点击:

Move n characters from front of string to the end

javascriptjquerystring

提问by Malyo

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.

这似乎是一个简单的问题,但我找不到解决方案。我想先取字符串中的 2 个字母,然后将它们移到字符串的末尾。例如,OK12 将变为 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.

编辑:到目前为止,我已经尝试切断字符串,然后将其添加到字符串的其余部分,但我认为有一个单行解决方案,例如预定义的函数或其他东西。

回答by gdoron is supporting Monica

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

Generic solution:

通用解决方案:

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

Live DEMO

现场演示

回答by Phrogz

Various techniques:

各种技术:

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

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

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

回答by Marius Bal?ytis

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

回答by Mert Emir

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