js——string object attribute (2)

1. Common methods of string

1. trim(): Remove the spaces on the left and right sides of the characters in the string (the spaces inside the characters cannot be removed).

Two ways to check whether it is empty:

 <script>

        /* 第一种校验不能为空的方式 包括如输入空格 */
        let email = prompt('请输入邮箱')
           if(eamil.trim()==''){
           alert('输入不能为空')
         }


        /* 第二种校验不能为空的方式 包括如输入空格*/
        if(!eamil.trim().length){
            alert('输入不能为空')
        }else if(eamil.indexOf('@')||!email.includes('.')){
            alert('必须包含@和.')
        }
</script>

2. toLowerCase(): convert the string to lowercase, and return a lowercase string


3. toUpperCase(): convert the string to uppercase 


4. substring()    extracts the characters between two specified index numbers in the string

You can intercept the string and return the intercepted string (the original string has not changed, excluding the last character)


5. slice(): use the same method as substring, but you can use negative numbers to represent subscripts 


6. substr(): Extract the specified number of characters in the string from the starting index number (negative numbers can also be used) 


Small expansion:

Template string in es6: Wrap it with ` ` (backticks), the string is written normally, and wrap it with ${} when you encounter a variable.


Small exercise: (Three ways to complete the capitalization of the first letter) 

<body>
    <button onclick="un()">按钮</button>
    <script>
 
        /* 按钮函数方法 */
        function un(){
            let a = prompt('请输入类似于hello world格式');
            let arr = a.split(' ');
            let b = fn(arr[0]);
            let c = fn(arr[1]);
            let arr1 = [];
            arr1.push(b);
            arr1.push(c);
            document.write(arr1.join(' '));
 
            /* function fn(str) {
                let s1 = str.substring(0, 1).toUpperCase();
                let s2 = str.substring(1);
                let s = s1 + s2;
                return s;
            } */
            function fn(str) {
                let s1 = str.substr(0, 1).toUpperCase();
                let s2 = str.substr(1);
                let s = s1 + s2;
                return s;
            }
            /* function fn(str) {
                let s1 = str.slice(-str.length,-str.length+1).toUpperCase();
                let s2 = str.slice(-str.length+1);
                let s = s1 + s2;
                return s;
            } */
        }
    </script>
</body>

Guess you like

Origin blog.csdn.net/weixin_68485297/article/details/124453468