1

So I have a string (a room description) and would like to replace part <?player> of it with some new string (req.session.player).

Here is the code:

var description = "<?player>, you are in a room.";
description.replace("<?player>", req.session.player);

I have tested and the req.session.player does have string value.

When I do the replace method nothing changes. NOTE: I have also tried using /<?player>/ and this did not work either.

Any ideas?

Pranav 웃
  • 8,469
  • 6
  • 38
  • 48
vickimagoo
  • 33
  • 1
  • 5

3 Answers3

4

You must assign your variable to the new altered string, because replace doesn't update your variable:

var description = "<?player>, you are in a room.";
description = description.replace('<?player>', req.session.player);

Moreover, if you want to replace all occurrences of '<\?player>' instead of only the first one, then use a regular expression with g (global) flag:

var description = "<?player>, you are in a room.";
description = description.replace(/<\?player>/g, req.session.player);

For full information, read https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace. Some quotes:

Returns a new string with some or all matches of a pattern replaced by a replacement.

This method does not change the String object it is called on. It simply returns a new string.

To perform a global search and replace, either include the g switch in the regular expression

Community
  • 1
  • 1
Oriol
  • 274,082
  • 63
  • 437
  • 513
2

The problem is the returned value of the replace method is not assigned:

description = description.replace("<?player>", req.session.player);

JS Fiddle: http://jsfiddle.net/LEBRK/

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
1

replace method returns new string, so you need to assign it to your description variable:

var description = "<?player>, you are in a room.";

description = description.replace("<?player>", 'Bill'); // description now is "Bill, you are in a room."
aga
  • 27,954
  • 13
  • 86
  • 121
  • Somebody really has a problem with good advice today. There is no reason to downvote this. – Kevin Bowersox Nov 30 '13 at 21:36
  • @KevinBowersox the only reason someone could downvote this is because my answer doesn't add anything new to the previous posts. my apologise, silent downvoter - I didn't refresh the page before answering the question and didn't see that people already answered it. – aga Nov 30 '13 at 21:39
  • 2
    I think the issue is that the code didn't implement the recommendation originally. – woolstar Nov 30 '13 at 21:39
  • @woolstar it's two o'clock in the morning in my city, and I'm almost sleeping. thank you for the pointing out the issue in my answer! – aga Nov 30 '13 at 21:40