Javascript字符串替换不起作用

Javascript string replace not working

本文关键字:不起作用 替换 字符串 Javascript      更新时间:2024-01-10

所以我有一个字符串(房间描述),想用一些新的字符串(req.session.player)替换它的部分<?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.一些报价:

返回一个新字符串,其中pattern的部分或全部匹配项被replacement替换。

此方法不会更改调用它的String对象。它只是返回一个新字符串。

要执行全局搜索和替换,请在正则表达式中包含g开关

问题是没有分配replace方法的返回值:

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

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

replace方法返回新字符串,因此需要将其分配给description变量:

var description = "<?player>, you are in a room.";
description = description.replace("<?player>", 'Bill'); // description now is "Bill, you are in a room."