Skip navigation
Currently Being Moderated

Multiple replace in string

Feb 6, 2014 10:02 AM

Tags: #actionscript_3.0 #4.6

Hi!

I have a string like

/series/%seriesName%?pipeKey=%pipeKey%&kmbegin=%kmFrom%&kmend=%kmTo%&modekey=%modeKey%" 

 

And I want to replace variables with appropriate values. Now I do this with next code:

myString.replace("%seriesName%", seriesName).replace("%pipeKey%", pipeKey).replace("%kmFrom%", kmFrom).replace("%kmTo%", kmTo).replace("%modeKey%", modeKey);

 

Maybe there is shorter and prettier algorithm exists?

 

Thank you!

 
Replies
  • Currently Being Moderated
    Feb 6, 2014 8:55 PM   in reply to Craberoid

    Well, you could write a loop:

     

    
    var names:Array = ["seriesName", "pipeKey", "kmFrom", "kmTo", "modeKey"];
    for each (var name:String in names)
        myString = myString.replace("%" + name + "%", this[name]);
    

     

     
    |
    Mark as:
  • Currently Being Moderated
    Feb 7, 2014 6:33 PM   in reply to Craberoid

    also you can try this, use replace function

     

    var obj = {kmFrom: 1, kmTo: 2},
        myString = 'kmbegin=%kmFrom%&kmend=%kmTo%';
     
     
    function reaplacer(match, p1) {
        return obj[p1];
    }
     
    myString.replace(new RegExp('%(kmFrom|kmTo)%', 'g'), reaplacer);
    
     
    |
    Mark as:

More Like This

  • Retrieving data ...

Bookmarked By (0)

Answers + Points = Status

  • 10 points awarded for Correct Answers
  • 5 points awarded for Helpful Answers
  • 10,000+ points
  • 1,001-10,000 points
  • 501-1,000 points
  • 5-500 points