Thursday, April 20, 2017

TC Cup of Codes: Separate Numbers from a String in Javascript

So this morning, a friend asked how to separate numbers from a string using Javascript. He wants to use car plates as input, for example: "AB1234DCD" and wants the output to be "AB 1234 DCD".

After spent some time coding Googling with various possible algorithms keywords, I finally got the answer from.....http://stackoverflow.com. :D

Using split.(/(\d+)/) it will automatically split the string "AB1234DCD" into an array "AB", "1234", "DCD". And after that, you can do anything you want to the array. In the code below, I use join(" ") to append the array and add white space between each element.


  
1
2
3
4
5
6
7
8
9
function SplitPlate() {
   var plateOld = document.getElementById('oldPlate').value;
   arr = plateOld.split(/(\d+)/)
   plateFinal = arr.join(" ");
   //alert(test);
 
   var plateNew = document.getElementById('newPlate');
   plateNew.innerHTML = plateFinal;
 }
 

  
function SplitPlate() {
   var plateOld = document.getElementById('oldPlate').value;
   arr = plateOld.split(/(\d+)/)
   plateFinal = arr.join(" ");
   //alert(test);

   var plateNew = document.getElementById('newPlate');
   plateNew.innerHTML = plateFinal;
 }

0 comments:

Post a Comment