Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript – How to search for numbers greater than x in regex

I am trying to not to include numbers greater than 26 in my input. So if a user input 27 above in the input tag, it will not show on the result. How can i do it? Here is my code thank you!

Please separate the numbers using space, for example:
<br> 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 <br> Output: A B C D E F G H I J K L M N O P Q R S T U V W X Y Z <br><br><br>
<input type="text" id="inputNum"><br>
<button onclick="convert()">Convert to Letters</button>
<br>
<p id="result"></p>

<script>
  function convert() {
    let numbers = document.getElementById("inputNum").value;

    let outputVal = numbers.replace("10", "J").replace("11", "K").replace(/12/gi, "L").replace("13", "M").replace("14", "N").replace("15", "O").replace("16", "P").replace("17", "Q").replace("18", "R").replace("19", "S").replace("20", "T").replace("21", "U").replace("22", "V").replace("23", "W").replace("24", "X").replace("25", "Y").replace("26", "Z").replace(/1/gi, "A").replace(/2/gi, "B").replace("3", "C").replace("4", "D").replace("5", "E").replace("6", "F").replace("7", "G").replace("8", "H").replace("9", "I");

    document.getElementById("result").innerHTML = outputVal;
  }
</script>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’d suggest simplifying the logic using String.split(), and Array.reduce().

We can check each number to ensure it’s in range in the .reduce() call (>=0 and <= 26).

You can then use String.fromCharCode() to convert each number to a letter:

function convert() {
    let numbers = document.getElementById("inputNum").value.trim();
    let outputVal = numbers.split(/\s+/).reduce((acc, n) => {
        return acc + (((n >= 0) && (n <= 26)) ? String.fromCharCode(+n + 64) + ' ': '');
    }, '');
    document.getElementById("result").innerHTML = outputVal;
}
Please separate the numbers using space, for example:

<br> 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 <br> Output: A B C D E F G H I J K L M N O P Q R S T U V W X Y Z <br><br><br>
<input type="text" id="inputNum"><br>
<button onclick="convert()">Convert to Letters</button>
<br>
<p id="result"></p>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading