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

Detailed example of split string splitting function in JavaScript

coldplay.xixi
Release: 2020-06-15 15:25:45
forward
2919 people have browsed it

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)
Copy after login

Example one

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

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"]
Copy after login

Example 3

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

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>
Copy after login

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!

Related labels:
source:aiti.fun
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template