Hi,

> no String.insert method?

Correct, `String` doesn't intrinsically have an `insert` method.

> Is this the best way?  I don't really like it......

Pretty much, except that `substr` is not part of the standard (though
it's widely-supported, and it's noted in Appendix B, which is a non-
normative informational appendix); I'd probably use `substring`
instead. The only difference is that the second parameter in `substr`
is a length, whereas in `substring` it's the index of the first
character *not* to include. In both cases, if you leave the second arg
off, it goes to the end of the string.

So:

if (!String.prototype.insert) {
    (function() {
        String.prototype.insert = String_insert;
        function String_insert(index, str) {
            if (index <= 0) {
                // Insert at beginning
                return str + this;
            }
            else if (index >= this.length) {
                // "Insert" at end
                return this + str;
            }
            else {
                // Insert in the middle
                return this.substring(0, index) + str +
this.substring(index);
            }
        }
    })();
}

FWIW,
--
T.J. Crowder
Independent Software Consultant
tj / crowder software / com
www.crowdersoftware.com


On May 23, 7:18 pm, patrick <patrick99...@gmail.com> wrote:
> I was looking for a way to insert a string into another, and have not
> really found anything...
>
> Is this the best way?  I don't really like it......
>
> var str1 = "hello friend";
> var str2 = "my "
>
> str1.substr(0, 6) + str2 + str1.substr(6, str1.length);
> => "hello my friend"
>
> -patrick
>
> --
> You received this message because you are subscribed to the Google Groups 
> "Prototype & script.aculo.us" group.
> To post to this group, send email to prototype-scriptacul...@googlegroups.com.
> To unsubscribe from this group, send email to 
> prototype-scriptaculous+unsubscr...@googlegroups.com.
> For more options, visit this group 
> athttp://groups.google.com/group/prototype-scriptaculous?hl=en.

-- 
You received this message because you are subscribed to the Google Groups 
"Prototype & script.aculo.us" group.
To post to this group, send email to prototype-scriptacul...@googlegroups.com.
To unsubscribe from this group, send email to 
prototype-scriptaculous+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/prototype-scriptaculous?hl=en.

Reply via email to