在解码的 URI 十六进制代码上使用 replace() 与本机除法运算符



构建计算器。

var process = "6÷6";  // need to replace division sign with one that javascript can evaluate with
process = encodeURI(process);
process.replace(/%C3%B7/gi,'/'); // replacement step that doesn't work - %C3%B7 is what shows up as the hex divison sign in chrome debugger, not sure why
process = decodeURI(process);
result = eval(process);

您可以创建属性设置为算术运算符的对象。请注意,.replace()可能不是必需

var map = {"÷":"/"};
var operatorType = "÷";
var process = "6" + map[operatorType] + "6";  // need to replace division sign with one that javascript can evaluate with
process = encodeURI(process);
process.replace(/%C3%B7/gi,'/'); // replacement step that doesn't work - %C3%B7 is what shows up as the hex divison sign in chrome debugger, not sure why
process = decodeURI(process);
result = eval(process);
document.body.innerHTML = result;

代码的第三行是错误的。您必须将替换函数的返回值分配给变量。最简单的方法是将其分配给自己:

process = process.replace(/%C3%B7/gi,'/');

所以整个脚本代码看起来像这样:

var process = "6÷6";  // need to replace division sign with one that javascript can evaluate with
process = encodeURI(process);
process = process.replace(/%C3%B7/gi,'/'); // replacement step now works
process = decodeURI(process);
result = eval(process);

相关内容

最新更新