Antworten:
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);
Das Folgende kann verwendet werden, um textinnerhalb einer anderen Zeichenfolge indexmit einem optionalen removeCountParameter an einer gewünschten Stelle zu verbinden .
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('');, den OPs "Ich will einen Apfel" anstelle von "Ich will einen Apfel" zu geben.
var output = a.substring(0, position) + b + a.substring(position);
Bearbeiten: ersetzt .substrdurch .substringweil .substrist jetzt eine Legacy-Funktion (per https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr )
String.prototype.substrist jetzt veraltet. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
.substring
Sie können diese Funktion zur Zeichenfolgenklasse hinzufügen
String.prototype.insert_at=function(index, string)
{
return this.substr(0, index) + string + this.substr(index);
}
Damit Sie es für jedes Zeichenfolgenobjekt verwenden können:
var my_string = "abcd";
my_string.insertAt(1, "XX");
Die Verwendung von ES6-String-Literalen wäre viel kürzer:
const insertAt = (str, sub, pos) => `${str.slice(0, pos)}${sub}${str.slice(pos)}`;
console.log(insertAt('I want apple', ' an', 6)) // logs 'I want an apple'
Vielleicht ist es sogar noch besser, wenn Sie die Position mit indexOf () wie folgt bestimmen :
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";
}
Rufen Sie dann die Funktion folgendermaßen auf:
insertString("I want apple", "an ", "apple");
Beachten Sie, dass ich im Funktionsaufruf ein Leerzeichen nach dem "an" und nicht in die return-Anweisung setze.
Die Underscore.String- Bibliothek verfügt über eine Funktion zum Einfügen
Einfügen (Zeichenfolge, Index, Teilzeichenfolge) => Zeichenfolge
wie so
insert("Hello ", 6, "world");
// => "Hello world"
Versuchen
a.slice(0,position) + b + a.slice(position)
oder Regexp-Lösung
"I want apple".replace(/^(.{6})/,"$1 an")
var array = a.split(' ');
array.splice(position, 0, b);
var output = array.join(' ');
Dies wäre langsamer, kümmert sich jedoch um das Hinzufügen von Leerzeichen vor und nach dem. Außerdem müssen Sie den Wert der Position ändern (auf 2, es ist jetzt intuitiver).
Schnelle Lösung! Wenn Sie kein Leerzeichen manuell hinzufügen möchten, können Sie dies tun:
var a = "I want apple";
var b = "an";
var position = 6;
var output = [a.slice(0, position + 1), b, a.slice(position)].join('');
console.log(output);
(edit: ich sehe, dass dies oben tatsächlich beantwortet wird, sorry!)
Wenn das Lookbehind von ES2018 verfügbar ist , eine weitere Regexp-Lösung, die es verwendet, um an einer Position mit einer Breite von Null nach dem N-ten Zeichen zu "ersetzen" (ähnlich wie bei @Kamil Kiełczewski, jedoch ohne die Anfangszeichen in einer Erfassungsgruppe zu speichern):
"I want apple".replace(/(?<=^.{6})/, " an")
Nun, nur eine kleine Änderung, weil die oben genannten Lösungsausgaben
"Ich will einen Apfel"
anstatt
"Ich will einen Apfel"
Um die Ausgabe als zu erhalten
"Ich will einen Apfel"
Verwenden Sie den folgenden geänderten Code
var output = a.substr(0, position) + " " + b + a.substr(position);