String replace function question

For test results, bug reports, announcements of new builds etc.

Moderators: winston, another_commander, Getafix

Post Reply
User avatar
phkb
Impressively Grand Sub-Admiral
Impressively Grand Sub-Admiral
Posts: 4830
Joined: Tue Jan 21, 2014 10:37 pm
Location: Writing more OXPs, because the world needs more OXPs.

String replace function question

Post by phkb »

I have the following code.

Code: Select all

var mytext = "This is some text at the start @station@ some text in between @station@ and some text at the end.";
var msg = mytext.replace("@station@", station.displayName);
log(this.name, "result = " + msg);
When I run this code, the result is:

Code: Select all

result = This is some text at the start Coriolis Station some text in between @station@ and some text at the end.
I would have thought the replace function would have replaced every instance it finds, not just the first one. Or am I doing this wrong?
User avatar
cim
Quite Grand Sub-Admiral
Quite Grand Sub-Admiral
Posts: 4072
Joined: Fri Nov 11, 2011 6:19 pm

Re: String replace function question

Post by cim »

The JS replace function is really supposed to take a regex, rather than a string. You can use strings, but you lose a lot of the power of the replace function - like global replacement

Code: Select all

var msg = mytext.replace(/@station@/g, station.displayName);
Alternatively, in Oolite you can do

Code: Select all

var mytext = "This is some text at the start [station] some text in between [station] and some text at the end.";
var msg = expandDescription(mytext, { station: station.displayName });
If you have more than one replacement to do, this is probably easier, because you can do it all in one function call.

Code: Select all

var msg = expandDescription(mytext, {
    station: station.displayName,
    ship: ship.displayName,
    contact: this.$missionContact
});
another_commander
Quite Grand Sub-Admiral
Quite Grand Sub-Admiral
Posts: 6683
Joined: Wed Feb 28, 2007 7:54 am

Re: String replace function question

Post by another_commander »

Try like this:

Code: Select all

var mytext = "This is some text at the start @station@ some text in between @station@ and some text at the end.";
var msg = mytext.replace(/@station@/g, S.mainStation.displayName);
log(this.name, "result = " + msg);
User avatar
phkb
Impressively Grand Sub-Admiral
Impressively Grand Sub-Admiral
Posts: 4830
Joined: Tue Jan 21, 2014 10:37 pm
Location: Writing more OXPs, because the world needs more OXPs.

Re: String replace function question

Post by phkb »

Thanks cim and another_commander!
Post Reply