javascript javascript字符串删除位置X处的一个字符并添加到开始

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8941216/
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 05:04:58  来源:igfitidea点击:

javascript string remove a character at position X and add to start

javascriptjquery

提问by David19801

If I have a string and a number:

如果我有一个字符串和一个数字:

var str='Thisisabigstring';
var numb=7;

I'm trying to remove the character at position 'numb'from the string and then put it at the beginning of the string.

我试图'numb'从字符串中删除位置处的字符,然后将其放在字符串的开头。

Trying for output like:

尝试输出如下:

'aThisisbigstring';

How can I do this with javascript/jquery?

我怎样才能用 javascript/jquery 做到这一点?

采纳答案by Mateusz W

quick and dirty :)

又快又脏:)

var b = str.charAt(numb - 1) + str.substring(0, numb - 1) + str.substring(numb);

回答by sjngm

var str = "Thisisabigstring";
var numb=7;
var c = str.charAt(numb);
str = c + str.substr(0, numb) + str.substr(numb + 1);

回答by Sudhir Bastakoti


var s = "Thisisabigstring";
var index = 7;
var x = s.charAt(index) + s.substr(0, (index - 1)) + s.substr(index + 1);
alert(x);

回答by mR.idiOt

var testStr = your_Test_string;
var CharPosition = Ur_Char_Position;
var pullOutChar = testStr.charAt(CharPosition);
testStr = pullOutChar + str.substr(0, CharPosition) + str.substr(CharPosition + 1);

回答by James McLaughlin

Sometimes it's easier to convert a string to an Arraywhen doing things like this:

有时Array在执行以下操作时将字符串转换为 an 会更容易:

str = str.split('');
str.unshift(str.splice(numb - 1, 1));
str = str.join('');

回答by JuSchz

There is no function in javascript which do that. Try this :

javascript 中没有这样做的功能。试试这个 :

String.prototype.replaceCharAt=function(index, char){return this.substr(0, index) + char + this.substr(index+char.length);}

回答by Leigh Ciechanowski

var x = str.substring(7,8);
str = x + str;