-1

I'm trying to make my own programming language, but its not going that well. Some commands work, but other ones don't, and I don't understand why.

This is the script I use to create the programming language:

var result;

convert("popup:['hi']; get:['#hello']:hide;");

function convert(text) {
  result = text;
  a("popup:", "alert");
  a("[", "(");
  a("]", ")");
  a("get:", "document.querySelector");
  a(":hide", ".style.display = 'none'");
  a(":show", ".style.display = 'block'");
  a(":html:", ".innerHTML = ");
  eval(result);
}

function a(text, textb) {
  result = result.replace(text, textb);
}
<!doctype html>

<html>

<head>
  <meta charset="utf-8">

  <title>Blank template</title>

  <!-- Load external CSS styles -->
  <link rel="stylesheet" href="styles.css">

</head>

<body>

  <h1 id="hello">hello there</h1>

  <!-- Load external JavaScript -->
  <script src="index.js"></script>

</body>

</html>
isherwood
  • 58,414
  • 16
  • 114
  • 157
  • 1
    [replace](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace) only replaces the first occurrence it finds. If you want to replace more then one you have to use a regex or switch to the [replaceAll](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll) method – Reyno Feb 27 '23 at 20:01
  • that litterally fixes the problem, thanks! – denoryprogrammer Feb 27 '23 at 20:03
  • Please revise your post title to ask a clear, specific question. Your issue is apparently with the replace function and not your "language". See [ask]. Also, the `result` variable doesn't seem to have a purpose. You can just evaluate the value passed into the function. – isherwood Feb 27 '23 at 20:07

1 Answers1

1

The issue is you're not replacing all instances of [] with () because .replace() only replaces the first instance.

You can use String.prototype.replaceAll():

result = result.replaceAll(text, textb);

For future debugging you need to look at the console (F12) for errors, because this would have given you a clue as to what the problem was.

Your original code would produce this string for eval():

alert('hi'); document.querySelector['#hello'].style.display = 'none';

As you can see it is trying to do querySelector['#hello']. This would produce the error:

Uncaught TypeError: Cannot read properties of undefined (reading 'style')

MrCode
  • 63,975
  • 10
  • 90
  • 112