View Full Version : replace certain part of string

06-27-2006, 04:03 PM
Hi, I can't find a javascript function to do this. Ideally I need the opposite of "charAt" to set the char at a specific position.

I've looked on google a lot but can only find examples of string replacing (at no specific position).

(also anyone know a downloadable javascript function reference?)


Bill Posters
06-27-2006, 04:43 PM
You may find that the substring method offers you a way to achieve your goal.


If we knew exactly how the script was intended to be implemented, then we could possibly put together a custom script for you.

06-27-2006, 04:55 PM
You may also use RegExp

Give us a small example of what you need, and, yes, we migh show u an example

06-27-2006, 05:18 PM
so there's no simple way?

here's what I have at the moment

var newstr = "";

for (x = 0; x < so.value.length; x ++)
if (x >= index && x < index+7)
newstr += colour.charAt(x-index);
else {
newstr += so.value.charAt(x);

so.value = newstr;
it replaces a colour in string "so.value" at position "index" with a different one "colour" (7 char hex code).

At the moment i'm looping through the whole string which takes a significant few seconds. (as there's several long strings)

06-27-2006, 06:20 PM
You could use string.replace using a regular expression

substr would probably be a lot faster than looping

But, I tried to figure it out, and it seems you can only read from random indeces, but not write to random indecex in a string.

06-28-2006, 05:07 PM
I see

so.value = so.value.substring(0, index) + colour + so.value.substring(index+7, so.value.length);

Thanks :) it's blazingly fast now.