javascripthtmlcharacter-replacement

Change Letters into Numbers seperated by commas?


I am trying to create a button that displays the text from the "TextCollector" input as numbers seperated by commas and ignores any symbol that is not in the alphabet. Update: I also need it to ignore the fact that a letter is capitalized.

Example:

a = 1

b = 2

c = 3

and so on...

So if I typed in "cat's" in the input at the bottom would display "3,1,20,19".

Here's what I've tried so far:

<form action="">
  <input type="text" id="TextCollector" name="TextCollector" placeholder="Type in something">
  <br>
  <input type="button" value="Submit" onclick="ShowMe()">
</form>


<h1 id="numbers"></h1>


<script>
  function ShowMe() {
    var text = document.getElementById("TextCollector").value;
    var textnum = text.charCodeAt(0) - 97;

    document.getElementById("numbers").innerHTML = textnum;
  }

</script>

But the code I tried halfly works, it just displays the first letter as a number and ignores the rest. Also with my code "0" is "a", but I need "1" to be "a".

Can someone help me? I hope I made myself clear...


Solution

  • First .replace all non-alphabetical characters with the empty string, then you can turn the resulting string into an array, .map each character to its character code, and join it by commas:

    function ShowMe() {
      const replaced = document.getElementById("TextCollector").value.replace(/[^a-z]/gi, '').toLowerCase();
      document.getElementById("numbers").textContent = [...replaced]
        .map(char => char.charCodeAt(0) - 96)
        .join(', ');
    }
    <form action="">
      <input type="text" id="TextCollector" name="TextCollector" placeholder="Type in something">
      <br>
      <input type="button" value="Submit" onclick="ShowMe()">
    </form>
    
    
    <h1 id="numbers"></h1>