0

I have a string like "My <color>"
I want to replace "<color>" with "Orange".
I did

str = str.replace("<color>","Orange");  

but it doesn't work.

How to do it?

5
  • 2
    You want to... replace "", or nothing, with Orange? Or did you want to replace the white space, " "? Commented May 27, 2010 at 6:48
  • I have modified the question. SO automatically removes "less than sign" Commented May 27, 2010 at 7:27
  • It works great for me. (select the code and press ctrl+k to format it - this way it won't hide your angle brackets either). Commented May 27, 2010 at 9:23
  • Are you sure what you wrote doesn't work for you? "It works on my machine". Commented May 27, 2010 at 10:43
  • May be a dumb question, but are you sure you created an AS3 file? .replace isn't a string method in AS2 from my recollection. Otherwise, your pasted code works fine. Commented May 27, 2010 at 16:33

1 Answer 1

2

Answer to edited post:

So replace returns a copy of "replaced" string, it does not modify the original:

var string:String = "My <color>";
var replaced:String = string.replace("<color>", "Orange");
// My <color> My Orange
trace(string, replaced);

So you could do:

var str:String = "My <color>";
str = str.replace("<color>", "Orange");
// My Orange
trace(str);

Then str would be "My Orange"

Which is what your code says it does, but I think you didn't paste what you wrote or you have an error elsewhere in your program.


Answer to OP:

"" is an empty string, so you're basically saying "replace empty with Orange". A space is not empty. If you want "MyOrange", you'll want to use " " instead of "":

var str:String = "My ";
// MyOrange
trace(str.replace(" ", "Orange"));

If you want "My Orange" just append "Orange" to your string.

var str:String = "My ";
str += "Orange"
// My Orange
trace(str);

Can you provide some more input as to what your intended output should be so we can provide a more accurate answer?

Sign up to request clarification or add additional context in comments.

1 Comment

His angle brackets were stripped off.. check the edited question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.