String replace function question

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

Moderators: winston, another_commander, Getafix

Post Reply
User avatar
phkb
Commodore
Commodore
Posts: 2438
Joined: Tue Jan 21, 2014 10:37 pm
Location: [p]laying [h]ard and [k]icking [b]utt somewhere in G7...

String replace function question

Post by phkb » Sat Jan 24, 2015 5:52 am

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: 4018
Joined: Fri Nov 11, 2011 6:19 pm

Re: String replace function question

Post by cim » Sat Jan 24, 2015 9:08 am

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: 5400
Joined: Wed Feb 28, 2007 7:54 am

Re: String replace function question

Post by another_commander » Sat Jan 24, 2015 9:18 am

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
Commodore
Commodore
Posts: 2438
Joined: Tue Jan 21, 2014 10:37 pm
Location: [p]laying [h]ard and [k]icking [b]utt somewhere in G7...

Re: String replace function question

Post by phkb » Sat Jan 24, 2015 5:04 pm

Thanks cim and another_commander!

Post Reply