如何在JavaScript中使用正则表达式替换?
输入:
The is currency \2,501 and \245,870.
输出:
The is currency ¥2,501 and ¥245,870.
答案 0 :(得分:0)
反斜杠尝试转义以下字符。例如,\ n是换行符。
在您的情况下,您无法在字符串中找到反斜杠,因为您尝试转义以下“ 2”字符。在这种情况下,您必须编写两个反斜杠以逃避一个反斜杠,如下所示:
var str = 'The is currency \\2,501 and \\245,870.';
console.log(str.replace(/\\/g, '¥')); //you get it here like ¥ because HTML is already loaded
//or like follows:
var yen = document.querySelector('div').innerHTML;
console.log(str.replace(/\\/g, yen));
//or direct like follows:
console.log(str.replace(/\\/g, '¥'));
<div>¥</div>