String match in javascript

Status
Not open for further replies.

Sridhar_Rao

In the zone
Hello guys, I am stuck here.
The textarea element has some text value like this: Ak, Am, Co, Cfp, Ce, Cfm, Ao, ... etc. As you can see each significant value is separated by a comma.
I want to parse through this long string and extract each value separately into an array. I mean the array should be like this:

Code:
myarray[0]="Ak"
myarray[1]="Am"
myarray[2]="Co"
myarray[3]="Cfp"
myarray[4]="Ce"
myarray[5]="Cfm"
myarray[6]="Ao"
and so on. How can this be done in javascript? I know this can be done using regex pattern but I have no idea how to do it.
 

Bandu

Journeyman
I am not sure if you are looking for a regex only solution. Here is a non-regex solution that should work for you:

Code:
<HTML>
<head>
<script language="JavaScript">
	function testFunc()
	{
		var txt = document.abc.txtA1.value;
		var tmpTxt = '';
		var i=0;
		var retArr = new Array();
		while(txt.indexOf(",") >= 0)
		{
			tmpTxt = txt.substring(0, txt.indexOf(","));
			retArr[i++] = tmpTxt;
			txt = txt.substring(txt.indexOf(tmpTxt) + tmpTxt.length + 1, txt.length);
		}
		retArr[i++] = txt;
		alert('Your final array is: ' + retArr);
	}
	</script>
</head>
<body>
	<form name="abc">
		<input type='text' name="txtA1" id="txtA1" size=60 />
		<input type='button' name="butt1" value="To Array" onClick="testFunc();"/>
	</form>
</body>
</HTML>
 

n2casey

Super Hero - Super Powers
It can be done through regex also. Solution is just one line code.

Code:
var val = document.getElementById('textbox1').value;
        var arr = val.split(/,/g);
 
        for(i=0; i < arr.length; i++)
           alert(arr[i]);

In the above code, arr will be an array of resulting values.
 
Status
Not open for further replies.
Top Bottom