Results 1 to 2 of 2

Thread: RegExp - insert()?

  1. #1
    Join Date
    Jun 2008
    Posts
    589
    Thanks
    13
    Thanked 54 Times in 54 Posts
    Blog Entries
    1

    Default RegExp - insert()?

    Is there a function called 'insert()' anywhere in JavaScript already? Wherein the user enters a string and an offset and the string will be inserted in another string at that offset and it scoots the substring over so it is just like inserting a string into another? Here is syntax: insert("David ", 8);

    If there isn't such a function (or even if there is), I've been working on it, but can't figure it out. Alright, so in the function, I have a preset string like "Hi. I'm Robinson". I would like to insert "David " right before "Robinson" and scoot "Robinson" over. Here is the code:

    Code:
    function insert(txt, offset) {
    str = "Hi. I\'m Robinson";
    rep = str.substr(offset, txt.length);
    add1 = str.substr(offset);
    str = str.replace(/rep/i, txt);
    add2 = str.substr(offset+txt.length);
    str = str.replace(/add2/i, add1);
    alert(str);
    // should alert "Hi. I'm David Robinson"
    }
    I've highlighted the code where I want the variables 'rep' and 'add2' values to be placed. Is there any way to place a variable's value w/ RegExp or something? I've tried [$rep] and [$add2], and even rep = new RegExp("/" + str.substr(offset, txt.length) + "/i") and str = str.replace(rep, txt), but those don't work. Please help! If I am not making myself clear, let me know and I'll explain it better.

    -magicyte
    Last edited by magicyte; 12-23-2008 at 08:57 PM.

  2. #2
    Join Date
    Jun 2008
    Posts
    589
    Thanks
    13
    Thanked 54 Times in 54 Posts
    Blog Entries
    1

    Default insert()

    Nevermind. I found the answer here. I can't believe how stupid I am.

    *sighs*

    -magicyte

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •