JavaScriptの特定のインデックスで文字を置き換えるにはどうすればよいですか?

StackOverflow https://stackoverflow.com/questions/1431094

質問

文字列があり、 Hello world の場合、インデックス3の文字を置き換える必要があります。インデックスを指定して文字を置き換えるにはどうすればよいですか。

var str = "hello world";

次のようなものが必要です

str.replaceAt(0,"h");
役に立ちましたか?

解決

JavaScriptでは、文字列は不変です。つまり、変更できるコンテンツで新しい文字列を作成し、それを指す変数を割り当てることが最善です。

replaceAt()関数を自分で定義する必要があります:

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

次のように使用します:

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

他のヒント

JavaScriptには replaceAt 関数はありません。次のコードを使用して、指定した位置にある任意の文字列の任意の文字を置換できます。

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>

できません。位置の前後の文字を取り、新しい文字列に連結します:

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

ここには多くの答えがあり、それらはすべて2つの方法に基づいています。

  • METHOD1:2つの部分文字列を使用して文字列を分割し、それらの間に文字を詰め込みます
  • METHOD2:文字列を文字配列に変換し、1つの配列メンバーを置き換えて結合します

個人的には、これら2つの方法を異なるケースで使用します。説明させてください。

@FabioPhms:あなたの方法は私が最初に使用したものであり、多くの文字を含む文字列では悪いと思いました。しかし、質問は多くのキャラクターとは何ですか? 10個の「lorem ipsum」でテストしました。段落とそれは数ミリ秒かかりました。次に、10倍の大きさの文字列でテストしました-大きな違いはありませんでした。うーん。

@ vsync、@ Cory Mawhorter:コメントは明確です。しかし、再び、大きな文字列とは何ですか? 32 ... 100kbのパフォーマンスを向上させるには、この1つの文字置換操作にsubstring-variantを使用する必要があることに同意します。

しかし、かなりの数の交換をしなければならない場合はどうなりますか?

私は自分のテストを実行して、その場合の高速化を証明する必要がありました。 1000文字で構成される比較的短い文字列を操作するアルゴリズムがあるとします。平均して、その文字列の各文字が〜100回置換されると予想されます。したがって、次のようなコードをテストするコードは次のとおりです。

var str = "... {A LARGE STRING HERE} ...";

for(var i=0; i<100000; i++)
{
  var n = '' + Math.floor(Math.random() * 10);
  var p = Math.floor(Math.random() * 1000);
  // replace character *n* on position *p*
}

このためのフィドルを作成しました。これはこちらです。 TEST1(サブストリング)とTEST2(配列変換)の2つのテストがあります。

結果:

  • TEST1:195ms
  • TEST2:6ms

配列変換は、サブストリングを2桁上回っているようです!それで、ここで何が起こったのでしょうか?

実際に起こるのは、TEST2のすべての操作が、 strarr2 [p] = n のような割り当て式を使用して、配列自体で実行されることです。割り当ては、大きな文字列の部分文字列と比較して非常に高速であり、勝つことは明らかです。

つまり、仕事に適したツールを選択することがすべてです。再び。

ベクターの操作は、通常、Stringに接続するのに最も効果的です。

次の機能をお勧めします:

String.prototype.replaceAt=function(index, char) {
    var a = this.split("");
    a[index] = char;
    return a.join("");
}

このスニペットを実行します:

String.prototype.replaceAt=function(index, char) {
    var a = this.split("");
    a[index] = char;
    return a.join("");
}

var str = "hello world";
str = str.replaceAt(3, "#");

document.write(str);

Javascriptでは文字列は不変なので、次のようなことをしなければなりません

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

xのiの文字を「h」に置き換えるには

str = str.split('');
str[3] = 'h';
str = str.join('');

function dothis() {
  var x = document.getElementById("x").value;
  var index = document.getElementById("index").value;
  var text = document.getElementById("text").value;
  var arr = x.split("");
  arr.splice(index, 1, text);
  var result = arr.join("");
  document.getElementById('output').innerHTML = result;
  console.log(result);
}
dothis();
<input id="x" type="text" value="White Dog" placeholder="Enter Text" />
<input id="index" type="number" min="0"value="6" style="width:50px" placeholder="index" />
<input id="text" type="text" value="F" placeholder="New character" />
<br>
<button id="submit" onclick="dothis()">Run</button>
<p id="output"></p>

この方法は短い文字列には適していますが、長いテキストには時間がかかる場合があります。

var x = "White Dog";
var arr = x.split(""); // ["W", "h", "i", "t", "e", " ", "D", "o", "g"]
arr.splice(6, 1, 'F');
var result = arr.join(""); // "White Fog"

/* 
  Here 6 is starting index and 1 is no. of array elements to remove and 
  final argument 'F' is the new character to be inserted. 
*/

String.replaceとコールバックを使用したワンライナー(絵文字サポートなし):

// 0 - index to replace, 'f' - replacement string
'dog'.replace(/./g, (c, i) => i == 0? 'f': c)
// "fog"

説明:

//String.replace will call the callback on each pattern match
//in this case - each character
'dog'.replace(/./g, function (character, index) {
   if (index == 0) //we want to replace the first character
     return 'f'
   return character //leaving other characters the same
})

@CemKalyoncu:すばらしい回答をありがとう!

また、Array.spliceメソッドのように少し変更しました(そして@Atesのメモを考慮しました):

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!"

これは、 Array.splice と同様に機能します。

String.prototype.splice = function (i, j, str) {
    return this.substr(0, i) + str + this.substr(j, this.length);
};

文字列内の文字を置換する場合は、可変文字列を作成する必要があります。これらは基本的に文字配列です。ファクトリを作成できます:

  function MutableString(str) {
    var result = str.split("");
    result.toString = function() {
      return this.join("");
    }
    return result;
  }

その後、文字にアクセスでき、文字列として使用すると配列全体が文字列に変換されます:

  var x = MutableString("Hello");
  x[0] = "B"; // yes, we can alter the character
  x.push("!"); // good performance: no new string is created
  var y = "Hi, "+x; // converted to string: "Hi, Bello!"

試すことができます

var strArr = str.split("");

strArr[0] = 'h';

str = strArr.join("");

私はあなたが尋ねるのと似たようなことをする関数を実行しました。文字列の文字が許可されていない文字の配列にあるかどうかをチェックします。

    var validate = function(value){
        var notAllowed = [";","_",">","<","'","%","<*>quot;,"&","/","|",":","=","*"];
        for(var i=0; i<value.length; i++){
            if(notAllowed.indexOf(value.charAt(i)) > -1){
               value = value.replace(value.charAt(i), "");
               value = validate(value);
            }
       }
      return value;
   }

これは古いことはわかっていますが、解決策は負のインデックスでは機能しないため、パッチを追加します。それが誰かを助けることを願っています

String.prototype.replaceAt=function(index, character) {
    if(index>-1) return this.substr(0, index) + character + this.substr(index+character.length);
    else return this.substr(0, this.length+index) + character + this.substr(index+character.length);

}

Kth インデックス(0ベースのインデックス)を 'Z' に置き換えたいとしましょう。 これを行うには、 Regex を使用できます。

var re = var re = new RegExp("((.){" + K + "})((.){1})")
str.replace(re, "$1A

Kth インデックス(0ベースのインデックス)を 'Z' に置き換えたいとしましょう。 これを行うには、 Regex を使用できます。

");

これはRegExpで簡単に実現できます!

const str = 'Hello RegEx!';
const index = 11;
const replaceWith = 'p';

//'Hello RegEx!'.replace(/^(.{11})(.)/, `$1p`);
str.replace(new RegExp(`^(.{${ index }})(.)`), `$1${ replaceWith }`);

//< "Hello RegExp"

react / javascriptのインデックスで単語や個々の文字のスタイルを設定する場合に思いついたバージョンです。

replaceAt( yourArrayOfIndexes, yourString/orArrayOfStrings ) 

作業例: https://codesandbox.io/s/ov7zxp9mjq

function replaceAt(indexArray, [...string]) {
    const replaceValue = i => string[i] = <b>{string[i]}</b>;
    indexArray.forEach(replaceValue);
    return string;
}

そして、これは別の代替方法です

function replaceAt(indexArray, [...string]) {
    const startTag = '<b>';
    const endTag = '</b>';
    const tagLetter = i => string.splice(i, 1, startTag + string[i] + endTag);
    indexArray.forEach(tagLetter);
    return string.join('');
}

その他...

function replaceAt(indexArray, [...string]) {
    for (let i = 0; i < indexArray.length; i++) {
        string = Object.assign(string, {
          [indexArray[i]]: <b>{string[indexArray[i]]}</b>
        });
    }
    return string;
}

Afanasii Kurakinの答えを一般化すると、次のようになります。

function replaceAt(str, index, ch) {
    return str.replace(/./g, (c, i) => i == index ? ch : c)
}

let str = 'Hello World'
str = replaceAt(str, 1, 'u')
console.log(str) // Hullo World

正規表現と置換関数の両方を展開して説明しましょう:

function replaceAt(str, index, newChar) {
    function replacer(origChar, strIndex) {
        if (strIndex === index)
            return newChar
        else
            return origChar
    }
    return str.replace(/./g, replacer)
}

let str = 'Hello World'
str = replaceAt(str, 1, 'u')
console.log(str) // Hullo World

正規表現は正確に1文字に一致します。 g は、forループ内のすべての文字に一致させます。 replacer 関数は、元の文字と文字列内のその文字のインデックスを指定して呼び出されます。単純な if ステートメントを作成して、 origChar または newChar のどちらを返すかを決定します。

文字列型を拡張して、差し込みメソッドを含めることができます。

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

var s = "new function";
alert(s.insert(4,"insert string "));

その後、関数を呼び出すことができます:

次の関数を使用して、文字列の特定の位置にある Character または String を置き換えることができます。次のすべての一致ケースを置き換えるには、 String.prototype.replaceAllMatches() 関数を使用します。

String.prototype.replaceMatch = function(matchkey, replaceStr, matchIndex) {
    var retStr = this, repeatedIndex = 0;
    for (var x = 0; (matchkey != null) && (retStr.indexOf(matchkey) > -1); x++) {
        if (repeatedIndex == 0 && x == 0) {
            repeatedIndex = retStr.indexOf(matchkey);
        } else { // matchIndex > 0
            repeatedIndex = retStr.indexOf(matchkey, repeatedIndex + 1);
        }
        if (x == matchIndex) {
            retStr = retStr.substring(0, repeatedIndex) + replaceStr + retStr.substring(repeatedIndex + (matchkey.length));
            matchkey = null; // To break the loop.
        }
    }
    return retStr;
};

テスト:

var str = "yash yas $dfdas.**";

console.log('Index Matched replace : ', str.replaceMatch('as', '*', 2) );
console.log('Index Matched replace : ', str.replaceMatch('y', '~', 1) );

出力:

Index Matched replace :  yash yas $dfd*.**
Index Matched replace :  yash ~as $dfdas.**

ここでの方法は複雑です。 私はこのようにします:

var myString = "this is my string";
myString = myString.replace(myString.charAt(number goes here), "insert replacement here");

これは簡単です。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top