View Full Version : Resolved RegExp - insert()?

12-23-2008, 05:41 PM
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:

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


12-23-2008, 07:04 PM
Nevermind. I found the answer here (http://answers.yahoo.com/question/index?qid=20071005123124AA6KOnP). I can't believe how stupid I am.

:rolleyes: *sighs*