Hoe kan ik een string invoegen bij een specifieke index van een andere string?
var txt1 = "foo baz"
Stel dat ik “bar” wil invoegen na de “foo”, hoe kan ik dat bereiken?
Ik dacht aan substring()
, maar er moet een eenvoudigere, meer rechttoe rechtaan manier zijn.
Antwoord 1, autoriteit 100%
Je zou je eigen splice()
kunnen prototypen in String.
Polyfill
if (!String.prototype.splice) {
/**
* {JSDoc}
*
* The splice() method changes the content of a string by removing a range of
* characters and/or adding new characters.
*
* @this {String}
* @param {number} start Index at which to start changing the string.
* @param {number} delCount An integer indicating the number of old chars to remove.
* @param {string} newSubStr The String that is spliced in.
* @return {string} A new string with the spliced substring.
*/
String.prototype.splice = function(start, delCount, newSubStr) {
return this.slice(0, start) + newSubStr + this.slice(start + Math.abs(delCount));
};
}
Voorbeeld
String.prototype.splice = function(idx, rem, str) {
return this.slice(0, idx) + str + this.slice(idx + Math.abs(rem));
};
var result = "foo baz".splice(4, 0, "bar ");
document.body.innerHTML = result; // "foo bar baz"
Antwoord 2, autoriteit 92%
Invoegen bij een specifieke index (in plaats van, bijvoorbeeld, op het eerste ruimtekarakter) moet het gebruiken van string-snijden / substring:
var txt2 = txt1.slice(0, 3) + "bar" + txt1.slice(3);
Antwoord 3, Autoriteit 50%
Hier is een methode die ik heb geschreven die gedraagt als alle andere programmeertalen:
String.prototype.insert = function(index, string) {
if (index > 0) {
return this.substring(0, index) + string + this.substr(index);
}
return string + this;
};
//Example of use:
var something = "How you?";
something = something.insert(3, " are");
console.log(something)
Antwoord 4, Autoriteit 28%
Maak gewoon de volgende functie:
function insert(str, index, value) {
return str.substr(0, index) + value + str.substr(index);
}
en gebruik het dan zoals dat:
alert(insert("foo baz", 4, "bar "));
output: foo bar baz
Het gedraagt zich precies, zoals de C # (Sharp) String.Sert (INT STARTIDEX, String-waarde).
Opmerking: Deze invoegfunctie voegt de string waarde (derde parameter) vóór de opgegeven integer index ( Tweede parameter) in de string Str (eerste parameter) en retourneert vervolgens de nieuwe tekenreeks zonder str te wijzigen!
Antwoord 5, Autoriteit 6%
Als iemand op zoek is naar een manier om tekst op meerdere indices in een string in te voegen, probeer dit dan eens:
String.prototype.insertTextAtIndices = function(text) {
return this.replace(/./g, function(character, index) {
return text[index] ? text[index] + character : character;
});
};
U kunt dit bijvoorbeeld gebruiken om <span>
-tags op bepaalde offsets in een string in te voegen:
var text = {
6: "<span>",
11: "</span>"
};
"Hello world!".insertTextAtIndices(text); // returns "Hello <span>world</span>!"
Antwoord 6, autoriteit 6%
UPDATE 2016:Hier is nog een voor de lol(maar serieuzer!) prototypefunctie gebaseerd op one-liner RegExp
-benadering (met ondersteuning vooraf op undefined
of negatieve index
):
/**
* Insert `what` to string at position `index`.
*/
String.prototype.insert = function(what, index) {
return index > 0
? this.replace(new RegExp('.{' + index + '}'), '$&' + what)
: what + this;
};
console.log( 'foo baz'.insert('bar ', 4) ); // "foo bar baz"
console.log( 'foo baz'.insert('bar ') ); // "bar foo baz"
Vorige (terug naar 2012) voor de loloplossing:
var index = 4,
what = 'bar ';
'foo baz'.replace(/./g, function(v, i) {
return i === index - 1 ? v + what : v;
}); // "foo bar baz"
Antwoord 7, autoriteit 6%
Dit doet in feite wat @Base33 doet, behalve dat ik ook de mogelijkheid geef om een negatieve index te gebruiken om vanaf het einde te tellen. Een beetje zoals de substr-methode toestaat.
// use a negative index to insert relative to the end of the string.
String.prototype.insert = function (index, string) {
var ind = index < 0 ? this.length + index : index;
return this.substring(0, ind) + string + this.substr(ind);
};
Voorbeeld:
Stel dat u afbeeldingen op volledige grootte heeft met een naamgevingsconventie, maar de gegevens niet kunt bijwerken om ook miniatuur-URL’s op te geven.
var url = '/images/myimage.jpg';
var thumb = url.insert(-4, '_thm');
// result: '/images/myimage_thm.jpg'
Antwoord 8, autoriteit 3%
Gezien uw huidige voorbeeld zou u het resultaat kunnen bereiken door ofwel
var txt2 = txt1.split(' ').join(' bar ')
of
var txt2 = txt1.replace(' ', ' bar ');
maar aangezien je zulke veronderstellingen kunt maken, kun je net zo goed direct naar het voorbeeld van Gullen gaan.
In een situatie waarin je echt geen andere veronderstellingen kunt maken dan op karakterindexen, dan zou ik echt voor een substringoplossing gaan.
Antwoord 9, autoriteit 3%
my_string = "hello world";
my_insert = " dear";
my_insert_location = 5;
my_string = my_string.split('');
my_string.splice( my_insert_location , 0, my_insert );
my_string = my_string.join('');
https://jsfiddle.net/gaby_de_wilde/wz69nw9k/
Antwoord 10, autoriteit 2%
Ik weet dat dit een oude thread is, maar hier is een echt effectieve aanpak.
var tn = document.createTextNode("I am just to help")
t.insertData(10, "trying");
Het mooie hiervan is dat het de node-inhoud dwingt. Dus als dit knooppunt al op de DOM staat, hoeft u geen queryselectors te gebruiken of de innerText bij te werken. De wijzigingen zouden weerspiegelen vanwege de binding.
Als je een string nodig hebt, ga dan naar de eigenschap text content van het knooppunt.
tn.textContent
#=> "I am just trying to help"
Antwoord 11, autoriteit 2%
Nou, we kunnen zowel de substring- als de slice-methode gebruiken.
String.prototype.customSplice = function (index, absIndex, string) {
return this.slice(0, index) + string+ this.slice(index + Math.abs(absIndex));
};
String.prototype.replaceString = function (index, string) {
if (index > 0)
return this.substring(0, index) + string + this.substr(index);
return string + this;
};
console.log('Hello Developers'.customSplice(6,0,'Stack ')) // Hello Stack Developers
console.log('Hello Developers'.replaceString(6,'Stack ')) //// Hello Stack Developers
Het enige probleem van een substringmethode is dat deze niet werkt met een negatieve index. Het is altijd een string-index vanaf de 0e positie.
Antwoord 12, autoriteit 2%
- Maak een array van de string
- Gebruik Array#splice
- Stringify opnieuw met Array#join
De voordelen van deze aanpak zijn tweeledig:
- Eenvoudig
- Compatibel met Unicode-codepunt
const pair = Array.from('USDGBP')
pair.splice(3, 0, '/')
console.log(pair.join(''))
Antwoord 13
Je kunt reguliere expressies gebruiken met een dynamischpatroon.
var text = "something";
var output = " ";
var pattern = new RegExp("^\\s{"+text.length+"}");
var output.replace(pattern,text);
uitgangen:
"something "
Dit vervangt text.length
van witruimtetekens aan het begin van de string output
.
De RegExp
betekent ^\
– begin van een regel \s
elk witruimteteken, {n}
keer herhaald , in dit geval text.length
. Gebruik \\
om \
backslashes te escapen bij het bouwen van dit soort patronen uit strings.
Antwoord 14
Je kunt het gemakkelijk doen met regexp in één regel code
const str = 'Hello RegExp!';
const index = 6;
const insert = 'Lovely ';
//'Hello RegExp!'.replace(/^(.{6})(.)/, `$1Lovely $2`);
const res = str.replace(new RegExp(`^(.{${index}})(.)`), `$1${insert}$2`);
console.log(res);
Antwoord 15
Nog een oplossing, snijd de tekenreeks in 2 en plaats een tekenreeks ertussen.
var str = jQuery('#selector').text();
var strlength = str.length;
strf = str.substr(0 , strlength - 5);
strb = str.substr(strlength - 5 , 5);
jQuery('#selector').html(strf + 'inserted' + strb);
Antwoord 16
Slice gebruiken
U kunt slice(0,index) + str + slice(index)
gebruiken. Of u kunt er een methode voor maken.
String.prototype.insertAt = function(index,str){
return this.slice(0,index) + str + this.slice(index)
}
console.log("foo bar".insertAt(4,'baz ')) //foo baz bar
Antwoord 17
Ik wilde de methode vergelijken met behulp van substring en de methode met behulp van respectievelijk plak van Base33 en User113716, om dat te doen, schreef ik een code
Bekijk hier ook een kijkje op deze prestatie vergelijking, substring, plak
De gebruikte code creëert enorme snaren en voegt de snaar “bar” meerdere keren in de enorme string
if (!String.prototype.splice) {
/**
* {JSDoc}
*
* The splice() method changes the content of a string by removing a range of
* characters and/or adding new characters.
*
* @this {String}
* @param {number} start Index at which to start changing the string.
* @param {number} delCount An integer indicating the number of old chars to remove.
* @param {string} newSubStr The String that is spliced in.
* @return {string} A new string with the spliced substring.
*/
String.prototype.splice = function (start, delCount, newSubStr) {
return this.slice(0, start) + newSubStr + this.slice(start + Math.abs(delCount));
};
}
String.prototype.splice = function (idx, rem, str) {
return this.slice(0, idx) + str + this.slice(idx + Math.abs(rem));
};
String.prototype.insert = function (index, string) {
if (index > 0)
return this.substring(0, index) + string + this.substring(index, this.length);
return string + this;
};
function createString(size) {
var s = ""
for (var i = 0; i < size; i++) {
s += "Some String "
}
return s
}
function testSubStringPerformance(str, times) {
for (var i = 0; i < times; i++)
str.insert(4, "bar ")
}
function testSpliceStringPerformance(str, times) {
for (var i = 0; i < times; i++)
str.splice(4, 0, "bar ")
}
function doTests(repeatMax, sSizeMax) {
n = 1000
sSize = 1000
for (var i = 1; i <= repeatMax; i++) {
var repeatTimes = n * (10 * i)
for (var j = 1; j <= sSizeMax; j++) {
var actualStringSize = sSize * (10 * j)
var s1 = createString(actualStringSize)
var s2 = createString(actualStringSize)
var start = performance.now()
testSubStringPerformance(s1, repeatTimes)
var end = performance.now()
var subStrPerf = end - start
start = performance.now()
testSpliceStringPerformance(s2, repeatTimes)
end = performance.now()
var splicePerf = end - start
console.log(
"string size =", "Some String ".length * actualStringSize, "\n",
"repeat count = ", repeatTimes, "\n",
"splice performance = ", splicePerf, "\n",
"substring performance = ", subStrPerf, "\n",
"difference = ", splicePerf - subStrPerf // + = splice is faster, - = subStr is faster
)
}
}
}
doTests(1, 100)
Antwoord 18
Neem de oplossing. Ik heb deze code in een eenvoudig formaat geschreven:
const insertWord = (sentence,word,index) => {
var sliceWord = word.slice(""),output = [],join; // Slicing the input word and declaring other variables
var sliceSentence = sentence.slice(""); // Slicing the input sentence into each alphabets
for (var i = 0; i < sliceSentence.length; i++)
{
if (i === index)
{ // checking if index of array === input index
for (var j = 0; j < word.length; j++)
{ // if yes we'll insert the word
output.push(sliceWord[j]); // Condition is true we are inserting the word
}
output.push(" "); // providing a single space at the end of the word
}
output.push(sliceSentence[i]); // pushing the remaining elements present in an array
}
join = output.join(""); // converting an array to string
console.log(join)
return join;
}
Antwoord 19
Ramda gebruiken:
import { pipe, split, insert, join } from 'ramda';
const insertAtIndex = (strToInsert, index, str) =>
pipe(split(''), insert(index, strToInsert), join(''))(str)