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 ','