javascript - String .replace() does not work with '$' symbol
问题描述
So, I cannot figure out what is wrong? I know that .replace()
returns a new string, without mutable existing. It's really ridiculous, but I'm stuck on this. I need to replace '$' on '2', but it just concat string, not replace the value...
var answer_form = '$0';
var question_num = 2;
answer_form = answer_form.replace(/$/g, question_num);
console.log(answer_form);
解决方案
$
in regex means the end of a string. Use "
if you do not want to use regular expressions or escape the character like this: \$
.
var answer_form = '$0';
var question_num = 2;
answer_form = answer_form.replace(/\$/g, question_num);
console.log(answer_form);
推荐阅读
- javascript - React:在道具中传递的函数未定义
- c++ - 我的程序没有正确输出结构中的学生数量
- c# - 将 nameof 用于递归泛型类型的属性
- sql - SQL ORDER BY IN SELECT FROM STRING SPLIT 或逗号分隔值
- python - Python:检查用户输入猜测任何项目
- docker - docker 卷权限问题
- r - 导入并合并具有两列但长度不同的多个 .txt 文件
- javascript - React - 在带有图像和条形码的新选项卡上打开一个 html 页面
- powershell - PowerShell 进程,无需导出文件只是为了再次导入它
- macos - 如何强制 Mac 识别 USB 驱动器