首页 > 解决方案 > 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);

标签: javascript

解决方案


$ 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);


推荐阅读