Home  >  Article  >  Web Front-end  >  Detailed example of split string splitting function in JavaScript

Detailed example of split string splitting function in JavaScript

coldplay.xixi
coldplay.xixiforward
2020-06-15 15:25:452887browse

Detailed example of split string splitting function in JavaScript

split string splitting function in javascript

Assume that the string that needs to be split is: s="…. fs…fs….”, where fs represents the character or string used to separate.

Definition and usage

split() Method is used to split a string into a string array.

Grammar

stringObject.split(separator,howmany)

Example one

<script>
    var ss=s.split("fs");
    for(var i=0;i<ss.length;i++){
        //处理每一个 ss[i];
    }
</script>

Example two

In this example, we will split the structure more complexly `String:

"2:3:4:5".split(":") //将返回["2", "3", "4", "5"]
    "|a|b|c".split("|") //将返回["", "a", "b", "c"]

Example 3

<script>
    var str = "一二三四";
    var str1 = "篮球、排球、乒乓球";
    var arr = str.split("");//全部分割
    var arr1 = str1.split("、");//按照顿号分割
    var arr2 = str1.split("、",2);//按照顿号分割,保留两段
</script>

Example 4

<input id="x" type="text"/>
<input id="x" type="text"/><input type="button" onclick="x()" value="输入邮件地址,获取用户名"/>
<script>
<script>
function x(){
    var x=document.getElementById("x").value.toString();
    var c=x.split("@");
    document.getElementById("x").value=c[0];
}
</script>

Note: If the empty string ("") is used as a separator, then each stringObject characters will be separated.

Summary: The split function is very similar to the character splitting function in php and asp that we learned before. It can split the content we want into arrays as long as we use something as a dividing line.

Recommended tutorial: "js basic tutorial"

The above is the detailed content of Detailed example of split string splitting function in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:aiti.fun. If there is any infringement, please contact admin@php.cn delete