Question

I faced difficulties to replace a string.

var expression:String = '2X3';
var inString:String = expression;
inString=inString.replace("÷","/");
inString=inString.replace("X","*");
trace('Result.....',inString);

Output:- Result.....2*3

Its alright. But the problem was when i tried to give input as

var expression:String = '2X3X3X4X5X6';

output:-

Result.....2*3X3X4X5X6

But i need it in form of

Result.....2*3*3*4*5*6

and same for division. Thanks & Regards

Was it helpful?

Solution

I use this for replacing all

var result:String=inString.split("X").join("*");

OTHER TIPS

I know you've already selected a answer, but it lacked an explanation and a proper solution. The reason you see this happening is that String.replace(), when the pattern is a String, only replaces the first result. The solution is to use RegEx:

var expression:String = '2x3X3x4X5X6';
var result:String = expression.replace(/x/ig, "*");
trace(result); // output 2*3*3*4*5*6

The pattern uses two flags, global and case-insensitivity. That will grab all instances of the letter X, regardless of case, and search the entire string. The benefit with RegEx is that is extremely low level. There is little-to-no overhead when using a regular expression meaning they are incredibly fast. String.split and String.join use loops to function, I believe, which are considerably slower. Additionally, you have to store an additional array in memory.

Granted, these are negligible in most cases (difference in the 10's of microseconds, maybe), but not all. I had a project the required files to be scrambled. Unfortunately, the files were too large (200MB minimum) and the doing the replace().join() method was 4-5 slower than the RegEx method. With RegEx, I managed to reduce the lag while scrambling from a few seconds to 2-3 frames.

did you try inString=inString.replaceAll("X","*");? notice the "All" suffix!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top