PDA

View Full Version : Replace a character in a string


Bouch
04-03-2003, 05:29 PM
I need to replace the "+" sign with a space and use the new string in a variable.

Example: I have color names in variables that are used to send the color name to a shopping cart: "shirtColor1 = Black", "shirtColor2 = Blue+Dusk", "shirtColor3 = Lime+and+Asphalt". I also need to use the same variables to display the color name in a dynamic text field - without the "+" signs.

So, I need to filter out the "+" sign and replace it with a space and assign the filtered color name to a variable that is displayed in a text field.

I have made an object with my color name:
function colorconvert (colornumber) {
var color = eval("_root.code.shirtcolor" + colornumber);
colorCode = new String(color);, I just don't know what to do next.

Am I on the right track? How do I create a find and replace function that will work on a variable amount of "+" signs.

Thanks,
Mike

magicwand
04-03-2003, 06:05 PM
one simple solution is using substr
breakdown every letter and reconstruct them replacing "+"with" "

Bouch
04-03-2003, 07:14 PM
So, I would create a loop using the string length as a limit and on every pass check to see if the character is "chr(187)". When it is, how do I replace the "+" with a space?

Thanks

magicwand
04-03-2003, 07:48 PM
shirtColor3 = Lime+and+Asphalt".
for example;
for(i=0;i,i<shirtColor3.length;i++){
if (substr(shirtColor3,i,1) != "+"){
temp+=substr(shirtColor3,i,1)
}else{
temp+=" ";
}
}
trace(temp);

this is off my head so might be buggy.
try them

Bouch
04-07-2003, 03:39 PM
Thanks.

I'm almost there. Only for some reason,say for "Blue+Dusk", instead of looping from 1-9(length), it goes from 0-8, so, in the end, I get "BBlue Dus". Any ideas?

In the function below, 'colornumber' corresponds to the shirtcolor #. You can enter "5" when you call the function and it retrieves the color name. This is where I'm at now.


function colorconvert (colornumber) {
var color = eval("_root.code.shirtcolor" + colornumber);
colorBack = new String(color);
trace(colorBack); // eg. Blue+Dusk

for (i = 0; i < colorBack.length; i++) {
if (substring (colorBack, i, 1) != "+") {
colorFront += substring (colorBack, i, 1)
} else {
colorFront += " ";

}
trace (colorFront);
}
}


Outputs 'BBlue Dus'

magicwand
04-07-2003, 03:44 PM
try
for (i = 0; i <= colorBack.length; i++) {

Bouch
04-07-2003, 04:00 PM
This works:

for (i = 1; i <= colorBack.length; i++) {

Thanks for your help!

Here is the site I'm working on. The current version has old programming. Right now I'm reprogramming parts to make it better.

Mike

magicwand
04-07-2003, 04:04 PM
:):) good site.
good luck.

Nasia
01-14-2009, 09:00 AM
Hallo Bouch!


I used your code to replace some characters in a string but when I trace the created string I get "undefined" as a first character and the last one is not displayed.

You have faced the same problem?
Can you please help me out?

Thanks a lot.
N.