In this page it is presented a class with a method that can be used in JavaScript to split an alphanumeric string (a string with multiple pairs of sub-strings with: "Name Number", separated by certain characters).
This function separates the "Name" and "Number", and adds them into an object with two separated arrays ('name', and 'num') in their order from string.
- See the example and the comments in code.

Code of the class

// class to split an Alphanumeric string, from: https://coursesweb.net/javascript/
function splitStr() {
  /*
   - $str = the alphanumeric string,
   - $dlm1 = the character that separates the Name by Number
   - $dlm2 = the character that separates the pairs of sub-strings: "Name Number"

   Something like this:
       "Name[$dlm1]Number[$dlm2]Name[$dlm1]Number"
    - the delimiter character ($dlm1, and $dlm2) can be any character, for example: space character, dash, dot, comma, :, etc.
   This method returns an object with Names and Numbers from $str, separated in 2 arrays, in their order in string
  */
  this.splitNameNumber = function(str, dlm1, dlm2) {
    // JavaScript-jQuery course: https://coursesweb.net/javascript/
    // string with characters that must be escaped in RegExp pattern. If the delimiter character exists in chrs, escapes it
    var chrs = '.()[]<>?\'^*-+\\/';
    if(chrs.indexOf(dlm1) != -1) dlm1 = '\\'+dlm1;
    if(chrs.indexOf(dlm2) != -1) dlm2 = '\\'+dlm2;

    // sets the RegExp pattern used to separate the sub-strings, then the Name and Number from each sub-string
    var patt1 = new RegExp('([a-z \\._\\-'+ dlm1 + dlm2+ ']+[0-9]+)', 'ig');
    var patt2 = new RegExp('([a-z \\._\\-'+ dlm1+ ']+)([0-9]+)', 'ig');

    var substr = str.split(patt1);          // array with sub-strings

    if(substr != null && substr != '') {
      var re = {"name":[], "num":[]};              // variable for data to return
      var ir = 0;               // to define index of items in re
      nrsubstr = substr.length;      // number of matched substrings

      // traverse the matched sub-strings
      for(i=0; i<nrsubstr; i++) {
        // if not empty
        if(substr[i] != '') {
          var name_num = substr[i].split(patt2);       // array with separated Name and Number of each current sub-string

          // adds the Name and Number separated in the 2 arrays in re object
          if(name_num != '') {
            re['name'][ir] = trim(trim(name_num[1], dlm1));
            re['num'][ir] = name_num[2];
            ir++;
          }
        }
      }

      return re;
    }
    else return false;
  }

  // function to delete certain character from beginning and ending of a string
  var trim = function(str, chr) {
    var rgxtrim = (!chr) ? new RegExp('^\\s+|\\s+$', 'g') : new RegExp('^'+chr+'+|'+chr+'+$', 'g');
    return str.replace(rgxtrim, '');
  }
}
To use this class, first you must create an object using this syntax:
var objectName = new splitStr();
Then access the splitNameNumber() method, passing the string and delimiter characters:
var obNameNums = objectName.splitNameNumber(str, dlm1, dlm2);

• Here is a practical example of usage of this class.
In the example bellow it is used the splitNameNumber() method to separate the Names and Numbers from alphanumeric strings added in three DIVs. When it is clicked a button with event associated to each DIV, it is displayed a table with the Names and Numbers from that DIV.
- To get the string, create and display the HTML table, it is defined another function that uses the arrays returned by splitNameNumber() method of the "splitStr" class.
// String-1 with Name and Number separated by dot '.', and the sub-strings separated by comma ','
<div id="exstr1" style="margin:0 0 1em 3em;color:blue;">JavaScript-jQuery Course.2013, CoursesWeb.net.2011, MarPlo.net.2009</div>
// String-2 with Name and Number separated by space, and the sub-strings separated by comma ','
<div id="exstr2" style="margin:0 0 1em 3em;color:#00cb01;">Code Snippets 12, JavaScript Code 2011, MarPlo.net Courses 2009</div>
// String-3 with Name and Number, and the sub-strings separated by space
<div id="exstr3" style="margin:0 0 1em 3em;color:blue;">PHP_MySQL Tutorials 23 Ajax lessons 9 Web Development 2013</div>
<button id="exbtn1">String-1</button> - <button id="exbtn2">String-2</button> - <button id="exbtn3">String-3</button>
<div id="tbstr">Here it is displayed the table with Name and Numbers from strings.</div>

<script type="text/javascript">
// HERE add the splitStr class


// receives the ID of the HTML element with the string, and the delimiters for Name-Number and sub-strings
// creates and displays a HTML table
function reTable(idstr, dlm1, dlm2) {
  // gets the string
  var str = document.getElementById(idstr).innerHTML;

  // create an object of splitStr class, and uses the splitNameNumber() method
  var obSplitStr = new splitStr();
  var split_str = obSplitStr.splitNameNumber(str, dlm1, dlm2);

  var nrcol = split_str['name'].length;
  var htmltb = '<table cellpadding="2" cellspacing="0" border="1" style="margin:1em auto;border-color:#0001da;"><caption><b>'+idstr+'</b></caption><tr><th>Name</th><th>Number</th></tr>';

  // adds data from the arrays stored in split_str into HTML table
  for(var i=0; i<nrcol; i++) {
    htmltb += '<tr><td>'+ split_str['name'][i] +'</td><td>'+ split_str['num'][i] +'</td></tr>';
  }

  // adds the HTML table into the element with id="tbstr"
  document.getElementById('tbstr').innerHTML = htmltb +'</table>';
}

// register onclick event for each button
document.getElementById('exbtn1').onclick = function() { reTable('exstr1', '.', ','); }
document.getElementById('exbtn2').onclick = function() { reTable('exstr2', ' ', ','); }
document.getElementById('exbtn3').onclick = function() { reTable('exstr3', ' ', ' '); }
</script>
Demo, click on the buttons bellow.
// String-1 with Name and Number separated by dot '.', and the sub-strings separated by comma ','
JavaScript-jQuery Course.2013, CoursesWeb.net.2011, MarPlo.net.2009
// String-2 with Name and Number separated by space, and the sub-strings separated by comma ','
Code Snippets 12, JavaScript Code 2011, MarPlo.net Courses 2009
// String-3 with Name and Number, and the sub-strings separated by space
PHP_MySQL Tutorials 23 Ajax lessons 9 Web Development 2013
- -
Here it is displayed the table with Name and Numbers from strings.

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which attribute indicates that an input field must be filled out before submitting?
required="required" autofocus="autofocus" placeholder="text"
<input type="text" name="name1" required="required" />
Which CSS method increases or decreases the size of the HTML element (including its content)?
translate() scale() skew()
#some_id:hover {
  transform: scale(2, 1.5);
  -ms-transform: scale(2, 1.5);    /* IE 9 */
  -moz-transform: scale(2, 1.5);   /* Firefox */
}
Click on the Date object method that returns the day of the month.
setDate() getMonth() getDate()
var rightnow = new Date();
var day = rightnow.getDate();
alert(day);
Which function is used to upload a file on server?
is_file() move_uploaded_file() fopen()
if(move_uploaded_file($_FILES["field_name"]["tmp_name"], "dir/file_name")) {
  echo "The file succesfully uploaded";
}
Split an alphanumeric string into Array in JavaScript

Last accessed pages

  1. Get and Modify content of an Iframe (14290)
  2. Ajax MySQL CRUD Query Builder with Pagination (218)
  3. Script Users Register, Login, Online (16470)
  4. Get Mouse coordinates inside a Div or an Image (8102)
  5. PHP Unzipper - Extract Zip, Rar Archives (2126)

Popular pages this month

  1. Insert, Select and Update NULL value in MySQL (410)
  2. Read Excel file data in PHP - PhpExcelReader (329)
  3. PhpSpreadsheet - Read, Write Excel and LibreOffice Calc files (254)
  4. PHP getElementById and getElementsByTagName (205)
  5. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (198)