جافاسكريبت - إدراج سلسلة في فهرس محدد


كيف يمكنني إدراج سلسلة في فهرس محدد من سلسلة أخرى؟

 var txt1 = "foo baz"

افترض أنني أريد إدراج "bar " بعد "foo"، كيف يمكنني تحقيق ذلك؟

فكرت في substring()، لكن يجب أن يكون هناك طريقة أبسط وأكثر مباشرة.

الإجابة رقم 1

الإدراج عند فهرس محدد (بدلاً من، لنقل، عند أول حرف مسافة) يجب أن يستخدم تقطيع السلسلة/الجزء الفرعي:

var txt2 = txt1.slice(0, 3) + "bar" + txt1.slice(3);

الإجابة رقم 2

يمكنك تصميم نسخة أولية خاصة بك من splice() في النص.

تعبئة إضافية

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));
};

var result = "foo baz".splice(4, 0, "bar ");

document.body.innerHTML = result; // "foo bar baz"

تعديل: تم تعديله للتأكد من أن rem قيمة مطلقة.

الإجابة رقم 3

إليك طريقة كتبتها تتصرف مثل جميع لغات البرمجة الأخرى:

String.prototype.insert = function(index, string) {
  if (index > 0)
  {
    return this.substring(0, index) + string + this.substring(index, this.length);
  }

  return string + this;
};

//Example of use:
var something = "How you?";
something = something.insert(3, " are");
console.log(something)

مرجع:

  • http://coderamblings.wordpress.com/2012/07/09/insert-a-string-at-a-specific-index/

الإجابة رقم 4

فقط أنشئ الدالة التالية:

function insert(str, index, value) {
    return str.substr(0, index) + value + str.substr(index);
}

ثم استخدمه هكذا:

alert(insert("foo baz", 4, "bar "));

المخرجات: foo bar baz

يتصرف بالضبط مثل C# (Sharp) String.Insert(int startIndex, string value).

ملاحظة: تقوم هذه الدالة insert بإدراج النص value (المعامل الثالث) قبل العدد الصحيح المحدد index (المعامل الثاني) في النص str (المعامل الأول)، ثم تعيد النص الجديد دون تغيير str!

الإجابة رقم 5

  1. أنشئ مصفوفة من السلسلة
  2. استخدم Array#splice
  3. حوّل إلى سلسلة مرة أخرى باستخدام Array#join

فوائد هذا النهج مزدوجة:

  1. بسيط
  2. متوافق مع نقطة رمز يونيكود

const pair = Array.from('USDGBP')
pair.splice(3, 0, '/')
console.log(pair.join(''))

الإجابة رقم 6

هذا أساسًا ما يفعله @Base33 إلا أنني أعطي أيضًا خيار استخدام فهرس سلبي للعد من النهاية. نوعًا ما مثلما تسمح طريقة substr.

// 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);
};

مثال: لنفترض أن لديك صورًا بالحجم الكامل باستخدام نظام تسمية محدد ولكنك لا تستطيع تحديث البيانات لتزويد روابط الصور المصغرة أيضًا.

var url = '/images/myimage.jpg';
var thumb = url.insert(-4, '_thm');

//    result:  '/images/myimage_thm.jpg'

الإجابة رقم 7

تحديث 2016: هنا نموذج آخر للمتعة فقط (ولكن أكثر جدية!) لوظيفة أولية تعتمد على نهج RegExp السطر الواحد (مع دعم الإضافة في البداية على undefined أو 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"

الحل السابق (العودة إلى 2012) لِلْمُتَعَة فقط:

var index = 4,
    what  = 'bar ';

'foo baz'.replace(/./g, function(v, i) {
    return i === index - 1 ? v + what : v;
});  // "foo bar baz"

الإجابة رقم 8

إذا كان أي شخص يبحث عن طريقة لإدخال نص في عدة مؤشرات داخل سلسلة، جرب هذا:

String.prototype.insertTextAtIndices = function(text) {
    return this.replace(/./g, function(character, index) {
        return text[index] ? text[index] + character : character;
    });
};

على سبيل المثال، يمكنك استخدام هذا لإدراج وسوم <span> عند إزاحات معينة في سلسلة:

var text = {
    6: "<span>",
    11: "</span>"
};

"Hello world!".insertTextAtIndices(text); // returns "Hello <span>world</span>!"

الإجابة رقم 9

بالنظر إلى المثال الحالي لديك، يمكنك تحقيق النتيجة إما عن طريق

var txt2 = txt1.split(' ').join(' bar ')

أو

var txt2 = txt1.replace(' ', ' bar ');

ولكن بالنظر إلى أنه يمكنك إجراء مثل هذه الافتراضات، يمكنك أيضًا الانتقال مباشرة إلى مثال جولن.

في موقف لا يمكنك فيه حقًا إجراء أي افتراضات سوى تلك المستندة إلى فهرس الحرف، فسأذهب حقًا نحو حل السلسلة الجزئية.