所以我有一个字符串(房间描述)并想替换部分 <?player>
它带有一些新字符串( req.session.player
)。
代码如下:
var description = "<?player>, you are in a room.";
description.replace("<?player>", req.session.player);
我已经测试了 req.session.player
确实有字符串值。
当我执行替换方法时,没有任何变化。
注意:我也尝试过使用 /<?player>/
这也不起作用。
有什么想法吗?
您必须将您的变量分配给新更改的字符串,因为 replace
不更新您的变量:
var description = "<?player>, you are in a room.";
description = description.replace('<?player>', req.session.player);
此外,如果您想替换所有出现的 '<\?player>'
而不是只有第一个,然后使用正则表达式 g
(全局)标志:
var description = "<?player>, you are in a room.";
description = description.replace(/<\?player>/g, req.session.player);
有关完整信息,请阅读 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace .一些引述:
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