Robert Tan
Robert Tan

Reputation: 674

Using replace() on decoded URI hex codes with native division operator

Building a calculator.

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

Upvotes: 0

Views: 46

Answers (2)

eboye
eboye

Reputation: 313

The third line of your code is wrong. You have to assign the return value of the replace function to a variable. The easiest way is to assign it to itself:

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

So the whole script code would look like this:

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

Upvotes: 1

guest271314
guest271314

Reputation: 1

You can create an object with properties set to arithmetic operators. Note, .replace() may not be necessary

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;

Upvotes: 2

Related Questions