如何在JavaScript中的特定索引處替換字符?

我有一個字符串,比方說Hello world ,我須要在索引3處替換char。如何經過指定索引來替換char? html

var str = "hello world";

我須要相似的東西 ide

str.replaceAt(0,"h");

#1樓

@CemKalyoncu:感謝您的出色回答! 函數

我還對其進行了少量調整,使其更相似於Array.splice方法(並考慮了@Ates的注意事項): this

spliceString=function(string, index, numToDelete, char) {
      return string.substr(0, index) + char + string.substr(index+numToDelete);
   }

var myString="hello world!";
spliceString(myString,myString.lastIndexOf('l'),2,'mhole'); // "hello wormhole!"

#2樓

你不能 將位置先後的字符合併爲一個新字符串: spa

var s = "Hello world";
var index = 3;
s = s.substr(0, index) + 'x' + s.substr(index + 1);

#3樓

JavaScript中沒有replaceAt函數。 您能夠使用如下代碼在指定位置替換任何字符串中的任何字符: prototype

function rep() { var str = 'Hello World'; str = setCharAt(str,4,'a'); alert(str); } function setCharAt(str,index,chr) { if(index > str.length-1) return str; return str.substr(0,index) + chr + str.substr(index+1); }
<button onclick="rep();">click</button>


#4樓

在JavaScript中,字符串是不可變的 ,這意味着您能夠作的最好的事情就是用更改後的內容建立一個新的字符串,而後將變量分配給它。 code

您須要本身定義replaceAt()函數: orm

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

並像這樣使用它: htm

var hello="Hello World";
alert(hello.replaceAt(2, "!!")); //should display He!!o World

#5樓

在Javascript中,字符串是不可變的,所以您必須執行如下操做 索引

var x = "Hello world"
x = x.substring(0, i) + 'h' + x.substring(i+1);

將「 i」處的x中的字符替換爲「 h」

相關文章
相關標籤/搜索