回答:
var a = "I want apple";
var b = " an";
var position = 6;
var output = [a.slice(0, position), b, a.slice(position)].join('');
console.log(output);
以下は、オプションのパラメーターを使用して、text別の文字列内のでスプライスするために使用できます。indexremoveCount
if (String.prototype.splice === undefined) {
/**
* Splices text within a string.
* @param {int} offset The position to insert the text at (before)
* @param {string} text The text to insert
* @param {int} [removeCount=0] An optional number of characters to overwrite
* @returns {string} A modified string containing the spliced text.
*/
String.prototype.splice = function(offset, text, removeCount=0) {
let calculatedOffset = offset < 0 ? this.length + offset : offset;
return this.substring(0, calculatedOffset) +
text + this.substring(calculatedOffset + removeCount);
};
}
let originalText = "I want apple";
// Positive offset
console.log(originalText.splice(6, " an"));
// Negative index
console.log(originalText.splice(-5, "an "));
// Chaining
console.log(originalText.splice(6, " an").splice(2, "need", 4).splice(0, "You", 1));
.as-console-wrapper { top: 0; max-height: 100% !important; }
var output = [a.slice(0, position + 1), b, a.slice(position)].join('');、OPに「I wantan apple」ではなく「I wantan apple」を与えることです。
var output = a.substring(0, position) + b + a.substring(position);
編集:がレガシー関数になったために置き換えられ.substrまし.substringた.substr(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substrによる)
String.prototype.substrは非推奨になりました。developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/...
.substring
この関数を文字列クラスに追加できます
String.prototype.insert_at=function(index, string)
{
return this.substr(0, index) + string + this.substr(index);
}
これを任意の文字列オブジェクトで使用できるようにします。
var my_string = "abcd";
my_string.insertAt(1, "XX");
おそらく、次のようにindexOf()を使用して位置を決定する方が良いでしょう。
function insertString(a, b, at)
{
var position = a.indexOf(at);
if (position !== -1)
{
return a.substr(0, position) + b + a.substr(position);
}
return "substring not found";
}
次に、このような関数を呼び出します:
insertString("I want apple", "an ", "apple");
関数の呼び出しでは、returnステートメントではなく「an」の後にスペースを入れていることに注意してください。
試す
a.slice(0,position) + b + a.slice(position)
または正規表現ソリューション
"I want apple".replace(/^(.{6})/,"$1 an")
ES2018の後読みが利用できる場合、もう1つの正規表現ソリューションで、N番目の文字の後のゼロ幅の位置で「置換」します(@KamilKiełczewskiと似ていますが、最初の文字をキャプチャグループに保存しません):
"I want apple".replace(/(?<=^.{6})/, " an")
上記のソリューションが出力するので、まあ小さな変更です
"リンゴが欲しいです"
の代わりに
"リンゴが欲しいです"
出力を次のように取得するには
"リンゴが欲しいです"
次の変更されたコードを使用します
var output = a.substr(0, position) + " " + b + a.substr(position);