JS String Split


split() method of String Object splits a string into an array:

var s = "perschon.com";
var arr = s.split("m"); //arr is ["end","e","o.co"]
var arr = s.split("me"); //arr is ["end","mo.com"]


Following example will read the user input, and split the content by "\r\n", or "\n" if the former not detected, followed by ",", "\t" and " ".

<script language="javascript">
function split()
{
	var g1 = document.sp.g.value;
	var arr1 = new Array;
	if (g1.indexOf("\r\n") != -1)
	{arr1 = g1.split("\r\n");}
	else if (g1.indexOf("\n") != -1)
	{arr1 = g1.split("\n");}
	else if (g1.indexOf(",") != -1)
	{arr1 = g1.split(",");}
	else if (n.indexOf("\t") != -1)
	{arr1 = g1.split("\t");}
	else{arr1 = g1.split(" ");}
	for (var i=0; i<arr1.length; i++)
	{
		var line = i + 1;
		alert("Line " + line + " is: " + arr1[i]);
	}
}
</script>
<form name=sp>
<textarea style="width:400px; height:300px" name="g" cols="1" rows="10">
</textarea>
<input style="font-size: 17px" onclick="split()"
type="button" value="Test Code"/>
</form>


substr() method: cut string by a specified position and cut length:

var s = "perschon.com";
var x = s.substr(2,2); //x="dm"
var x = s.substr(2); //x="dmemo.com"


substring() method: cut string by two positions:

var s = "perschon.com";
var x = s.substring(2,4); //x="dm"
var x = s.substring(2); //x="dmemo.com"


slice(s,e) method: cut string, s - start position, e - end position (optional), if not provided, it's the end of the string:

var s = "perschon.com";
var s2 = arr.slice(2,5); //s2 is "dme"
var s2 = arr.slice(2); //s2 is "dmemo.com"


convert.idontcarewhatyouthink.net © 2021  Terms of Use | Home