Hi!!
i need to write a function that counts the number of names seperated by a '/'

for example if i write
aashish/ankush in a field
the number returned should be 2

thanks....

Dani AI

Generated

Good start: and pointed you in the right direction with splitting the names, and explored auto-inserting slashes. Below is a compact, modern approach that builds on those ideas but handles real-world edge cases: it counts non-empty name segments, formats the numbers field by inserting a "/" every 9 digits, caps the number of groups to the name count, preserves the caret (so typing/pasting doesn't jump the cursor), and works on paste as well as typing.

// count non-empty segments (ignores extra or leading/trailing slashes)
function countNames(str) {
  return (str || '').split('/').map(s => s.trim()).filter(Boolean).length;
}

function formatDigits(value, size, maxGroups) {
  const digits = value.replace(/\D/g, '').slice(0, size * maxGroups);
  const parts = [];
  for (let i = 0; i < digits.length; i += size) parts.push(digits.slice(i, i + size));
  return parts.join('/');
}

function preserveCaret(input, oldValue, oldPos) {
  const digitsBefore = oldValue.slice(0, oldPos).replace(/\D/g, '').length;
  const val = input.value;
  let seen = 0;
  for (let i = 0; i < val.length; i++) {
    if (/\d/.test(val[i])) seen++;
    if (seen === digitsBefore) { input.setSelectionRange(i + 1, i + 1); return; }
  }
  input.setSelectionRange(val.length, val.length);
}

// wire up (assumes inputs with ids "names" and "numbers")
const GROUP_SIZE = 9;
const namesEl = document.getElementById('names');
const numsEl = document.getElementById('numbers');

numsEl.addEventListener('input', function () {
  const old = this.value;
  const pos = this.selectionStart || 0;
  const maxGroups = Math.max(0, countNames(namesEl.value));
  this.value = formatDigits(old, GROUP_SIZE, maxGroups);
  preserveCaret(this, old, pos);
});

namesEl.addEventListener('input', () => {
  const maxGroups = Math.max(0, countNames(namesEl.value));
  numsEl.value = formatDigits(numsEl.value, GROUP_SIZE, maxGroups);
});

Notes and tips: use the input event instead of keypress so pastes are handled. If you saw the problem reported (extra characters after the allowed groups), that typically happens when checks run per keystroke and don't trim pasted content — slicing to size * maxGroups (as above) prevents it. For mobile, add inputmode="numeric" and pattern="\d*" to the numbers input to bring up the numeric keyboard. If you prefer an automatic trailing slash when a group completes, append one only when the digits length exactly equals GROUP_SIZE * groups (optional).

Recommended Answers

All 9 Replies

Hi
You can split the string with '/' and then you can get the length some thing like this

var names = "aashish/ankush";
var namesList = names.split('/');

namesList.length will return the count as 2

Regards
Anish

Hi
You can split the string with '/' and then you can get the length some thing like this

var names = "aashish/ankush";
var namesList = names.split('/');

namesList.length will return the count as 2

Regards
Anish

thanks...
the second part of the problem is , that now i have to write a function
where in i can enter only 9 digit numbers and after every ninth digit a "/" is automatically entered
the number of numbers i can enter is the count returned by the split function

You can try this code -->

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Content-Script-Type" content="text/javascript" />
<meta http-equiv="Content-Style-Type" content="text/css" />
<title>Test Page</title>

<style type="text/css">
/* <![CDATA[ */
html, body {
  background-color : #f0f0f0;
  border : none;
  color : #696969;
  font : normal normal normal 90%/1.6 Verdana, Tahoma, Helvetica, Arial, sans-serif;
  height : auto;
  min-height : 600px;
  min-width : 800px;
  text-align : center;
  vertical-align : baseline;
  width : auto; }

h2 {
  background-color : #ccc;
  border-bottom : 1px solid #708090;
  border-top : 1px solid #708090;
  font : 700 160% "Bernard MT Condensed";
  line-height : 2ex;
  margin-top : 0;
  min-height : 2ex;
  padding : .100em 0em .100em 1em;
  white-space : nowrap; }

div {
  border : none;
  margin : 0%;
  padding : 0%; }

div#main {
  margin : 0% auto;
  text-align : left;
  height : 100%;
  overflow : hidden;
  width : 98%; }

form {
  background-color : #ccc;
  padding : 1em;
  border : 1px solid;
  width : 30%; }

label, input {
  display : block; }

input {
  margin-bottom : .500em; }

div.tube {
  border : 1px solid #ccc;
  height : 600px;
  margin : 1% auto 1% auto;
  padding : 1.200em; }

/* ]]> */
</style>
<script type="text/javascript">
// <![CDATA[
var loose, num;
var splitTheNames;
var whatNames, thisNames, extractNames;
loose = Boolean();
   splitTheNames = function() {
   extractNames = function( whatNames ) {
   joinNumbers = function( whatNames ) {
   loose = 1; // Set this to "0" if you want to apply strict validation to the number field.
   num = new RegExp();
   setting = num.compile(("^\\d{" + (( loose ) ? "9," + (( 9 ) * whatNames.length ) : ( 9 * whatNames.length )) + "}$"));
   thisNumbers = (( document.getElementById ) ? document.getElementById("numbers") : document.all.numbers ); 
      if ( !setting.test( thisNumbers.value )) {
      alert("You must provide atleast a minimum characters of " + (( loose ) ? "9 or a maximum of " + (( 9 ) * whatNames.length ) + " characters long" : (( 9 ) * whatNames.length )) + " and must be a number.");
      thisNumbers.value = "";
      return false;
      } 
      numArray = thisNumbers.value.match(/(\d{9})/g); 
      thisNumbers.value = numArray.join("/");    
   }; 
   label = (( document.getElementById ) ? document.getElementById("label1") : document.all.label1 );
   label.innerHTML = "";
      try {
      txt = document.createTextNode( "Number Entry: " );
   iWidth = document.createAttribute("style");
      iWidth.nodeValue = "width : 100%";
   input = document.createElement("input");   
      input.type = "text";
   input.id = "numbers";
   input.name = "numbers";
   input.value = "";
   input.onchange = function() { joinNumbers( whatNames );
   };
   input.setAttributeNode( iWidth ); 
      label.appendChild( input );
      label.insertBefore( txt, input );
      } catch( e ) {
      label.innerHTML = 'Number Entry: <input type="text" id="numbers" name="numbers" value="" style="width : 100%" onchange="joinNumbers(' + whatNames + ');" />\n';
      }
   };
   thisNames = (( document.getElementById ) ? document.getElementById("names") : document.all.names );
   whatNames = thisNames.value.split(/[\,\/\s]+/); // Names can be splitted either by a ( space/backslash/comma ).
   if ( whatNames.length >= 1 ) {
   extractNames( whatNames ); 
   } 
};
// ]]>
</script>
</head>
<body>
<div id="main">
<div class="tube">
<h2>JavaScript Live DEMO!</h2>
<form id="frm" action="#" onsubmit="return false;">
<div>
<label for="names">Name Entry: <input type="text" id="names" name="names" value="" style="width : 100%;" onchange="splitTheNames();" /></label>
<label id="label1" for="numbers"></label>
</div>
</form>
</div>
</div>
</body>
</html>

Just be careful when you modify this code...

I forgot to include some backSlash in line #88:
simply change the entire line to this : thisNumbers.value = numArray.join("/") + "/";

This can easily be done using the split() method.

Here is an example:

function splitNames(names) {
	return names.split("/").length;
}

var names = "aashish/ankush";
alert("There are " + splitNames(names) + " names in the names list.");

The split() function has one parameter, separator , which defines the character(s) that you want to divide the text between. You could change this to anything, such as #*# so that your names string is:

aashish#*#ankush

hi @ essential...
thanks for all the effort...........
but your code always seems so compliacted to me...
i am jus a newbie :(
my fault.........

well i wrote this, to insert a / after a number as many times as the value of countname...

var count=0    

function countrelease()
{
  //alert("count name is " + countname )
  var strname = document.forms[0].RELEASE.value;
  var length = strname.length
  
  length=length-9
   
 if(count != countname)
  { 
   if (length % 10 == 0)
     {
      
        strname=strname + "/" 
        
      document.forms[0].RELEASE.value= strname;
      count=count+1
     }
    
  }
  else 
   { 
   
   event.returnValue = false;
   }
  
  //break;


 }

the problem is if countname is 2

i can type 123456789/987654321/1

where as i want the output to be
123456789/987654321

i am calling this function on keypress event !

The first code that i've provided is a cross-browser script. This moded (or simplified) version of the script, is based on the method's that you have used, in your last posted code.
All codes is as follows:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Content-Script-Type" content="text/javascript" />
<meta http-equiv="Content-Style-Type" content="text/css" />
<title>Test Page</title>

<style type="text/css">
/* <![CDATA[ */
html, body {
  background-color : #f0f0f0;
  border : none;
  color : #696969;
  font : normal normal normal 90%/1.6 Verdana, Tahoma, Helvetica, Arial, sans-serif;
  height : auto;
  min-height : 600px;
  min-width : 800px;
  text-align : center;
  vertical-align : baseline;
  width : auto; }
input label { display : block; }
input { margin-top : .200em; }

h2 {
  background-color : #ccc;
  border-bottom : 1px solid #708090;
  border-top : 1px solid #708090;
  font : 700 160% "Bernard MT Condensed";
  line-height : 2ex;
  margin-top : 0;
  min-height : 2ex;
  padding : .100em 0em .100em 1em;
  white-space : nowrap; }

div {
  border : none;
  margin : 0%;
  padding : 0%; }

div#main {
  margin : 0% auto;
  text-align : left;
  height : 100%;
  overflow : hidden;
  width : 98%; }

div.tube {
  border : 1px solid #ccc;
  height : 600px;
  margin : 1% auto 1% auto;
  padding : 1.200em; }
/* ]]> */
</style>
<script type="text/javascript">
// <![CDATA[
var splitTheNames;
splitTheNames = function() {
   numArray = [];
   strname = document.forms.myForm.names.value;

   num = document.forms.myForm.numbers.value;

   strname = strname.split(/[\/\s,]+/);
   extractNum = parseInt( num.length / 9 );
   if ( extractNum <=  strname.length ) {
      for ( var i = 0; i < extractNum; i++ ) {
       numArray[ i ] = num.match(/\d{9}/ig)[ i ]; document.forms.myForm.numbers.value = numArray.join("/") + "/"; 
      } return true;
   } else { 
   alert( "Numbers of characters must not exceed to " + ( strname.length * 9 ) + "." );
   document.forms.myForm.numbers.value = "";
    return false;
   } 
};
// ]]>
</script>
</head>
<body>
<div id="main">
<div class="tube">

<h2>JavaScript Live Demo</h2>
<form id="myForm" action="#" onsubmit="return false"
<div>
<label for="names">Name: <input type="text" id="names" name="names" size="30" onkeypress="splitTheNames();" /></label><br />
<label for="numbers">Numbers: <input type="text" id="numbers" name="numbers" size="30" /></label></div>
</form>
</div>
</div>
</body>
</html>

Just use the below script:

function pad()
{
    var txt=document.getElementById('<%= txt.ClientID %>');
    if(txt.value.replace(/\//g,"").length%2==0 && txt.value.length>0)
       txt.value=txt.value+'/';
}
<asp:TextBox runat="server" ID="txt" onkeypress="pad()"></asp:TextBox>

Here i showed how you can add pad / after each 2 character. Modify in your way.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.