javascript中字符串对象的常用方法

1、声明字符串

var string="hello world";

或var string='hello world';

2、在字符串中引用引号

单引号:var string="His name is 'tom' ";

双引号:var string='His name is "tom" ';

3、获得字符串的长度

document.write(string.length);

4、从下标为3的位置开始,截取4个字符,包括下标为3的位置的字符

document.write(string.substr(3,4));

5、从下标为6的位置开始截取,截取到下标为8的位置,但是不包括下标为8的字符

document.write(string.substring(6,8));

6、去掉字符串两边的空格,但是可能有浏览器不支持

document.write(string.trim().length);

7、字符串转换为大写

document.write(string.toUpperCase());

8、字符串转化为小写

document.write(string.toLowerCase());

9、分割字符串,返回一个数组

    document.write(name.split(" ")+"<br>");             //根据空格分割字符串
    document.write(name.split(" ").length+"<br>");  //分割后的数组长度
    document.write(name.split(" ")[0]+"<br>");         //打印数组。。。
    document.write(name.split(" ")[1]+"<br>");
    document.write(name.split(" ")[2]+"<br>");
    document.write(name.split(" ")[3]+"<br>");

猜你喜欢

转载自blog.csdn.net/zxr15709447338/article/details/87378481