JavaScript——字符串

2017-08-05  本文已影响18人  开心糖果的夏天

一、charAt

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>字符串</title>
<script type="text/javascript">
    var str1='abcdef';
    //alert(str1.charAt(0));弹出a
    alert(str1[0]);//不兼容IE6
</script>

</head>
<body>

</body>
</html>

二、charCodeAt

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>字符串</title>
<script type="text/javascript">
    var str1='abcdef';
    alert(str1.charCodeAt(0));//弹出a的码字
</script>

</head>
<body>

</body>
</html>

三、indexOf

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>字符串</title>
<script type="text/javascript">
    var str='abcade';
    alert(str.indexOf('a'));//找第一次出现的位置(弹出0)          没找到返回-1
    //alert(str.indexOf('cad'));
</script>

</head>
<body>

</body>
</html>

四、lastIndexOf

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>字符串</title>
<script type="text/javascript">
    var str='abcadea';
    alert(str.lastIndexOf('a'));//找最后一个出现的位置(弹出6)   没找到返回-1
</script>

</head>
<body>

</body>
</html>

五、length

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>字符串</title>
<script type="text/javascript">
    var str1='abc';
    //var str2=new String('abc');  //包装类
    alert(str1.length);//弹出3
</script>

</head>
<body>

</body>
</html>

六、match

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>字符串</title>
<script type="text/javascript">
    var str='12,456 rt 77 99';
    alert(str.match(/\d+/g));//选出数字  输出12,456,77,99
</script>

</head>
<body>

</body>
</html>

七、replace

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>字符串</title>
<script type="text/javascript">
    var str='abca';
    alert(str.replace('a','A'));//小写变大写(弹出Abca)
</script>

</head>
<body>

</body>
</html>

八、截取类(slice、substr 、substring)区别

slice 不取结束位置 把负数变为倒数第n个
substring 不取结束位置 把负数变为0,取全部字符
substr 取结束位置 把负数变为倒数第n个

<meta charset="utf-8">
<title>字符串</title>
<script type="text/javascript">
    var str='abcdef';
    alert(str.substring(-1));//负数直接变为0,取所有字符
</script>

</head>
<body>

</body>
</html>

九、toLowerCase()大写变小写 toUpperCase()小写变大写

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>字符串</title>
<script type="text/javascript">
    var str='GHHJHH';
    alert(str.toLowerCase());//弹出ghhjhh
</script>

</head>
<body>

</body>
</html>
上一篇下一篇

猜你喜欢

热点阅读