Javascript Course

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 tag is used to add lists into <ul> and <ol> elements?
<dt> <dd> <li>
<ul>
 <li>http://coursesweb.net/html/</li>
 <li>http://coursesweb.net/css/</li>
</ul>
Which value of the "display" property creates a block box for the content and ads a bullet marker?
block list-item inline-block
.some_class {
  display: list-item;
}
Which instruction converts a JavaScript object into a JSON string.
JSON.parse() JSON.stringify eval()
var obj = {
 "courses": ["php", "javascript", "ajax"]
};
var jsonstr = JSON.stringify(obj);
alert(jsonstr);    // {"courses":["php","javascript","ajax"]}
Indicate the PHP class used to work with HTML and XML content in PHP.
stdClass PDO DOMDocument
$strhtml = '<body><div id="dv1">CoursesWeb.net</div></body>';
$dochtml = new DOMDocument();
$dochtml->loadHTML($strhtml);
$elm = $dochtml->getElementById("dv1");
echo $elm->nodeValue;    // CoursesWeb.net
Split an alphanumeric string into Array in JavaScript

Last accessed pages

  1. Mysql SELECT JOIN tables on two different Databases (4498)
  2. jQuery UI draggable - Drag elements (11448)
  3. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (142520)
  4. Using the Bone Tool (4253)
  5. Node.js Move and Copy Directory (20134)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (523)
  2. The Mastery of Love (65)
  3. CSS cursor property - Custom Cursors (62)
  4. Read Excel file data in PHP - PhpExcelReader (59)
  5. PHP-MySQL free course, online tutorials PHP MySQL code (44)