javascript字符

Javascript学习系列文章,一方面作为学习记录,另一方面日后可以参考,所有内容均为个人的学习理解

字符串简介:

1、String类型,javascript引用类型之一。字符串,单引号双引号都可以。但是一单引号开始就的以单引号结束

'hello world"  //错误/

2、字符串一旦创建,值不能改变。要改变其实是销毁原来的字符串,然后再用另一个包含新值的字符串填充该变量

3、null undefined没有toString()方法,所以用String(str)方便。但是用 ‘’ + str是我们经常使用的方式

4、但是如果把数值转化为字符,且要输出任意有效进制格式表示的字符串,得用toString

var num = 2;
num.toString(2)  // '10'

5、字符串length属性表示字符串含有多少字符,双字节也会被当成一个字符,比如中文

字符方法:

1.访问字符串中单个字符

var str = 'hello'
str.charAt(1);  // 'e'
str.charCodeAt(1); // '101' 字符编码

IE8及其它浏览器,可以用[] 括号访问,就像数组一样

2.concat()用于连接字符串,其实用处不大,因为简洁都是用 '' + str  就可以连接了

3.slice()、substr()、substring()这三个方法,不对原字符串操作。功能就是裁剪出新字符串,都是两个参数。起始位置和结束位置。substr()特殊一点,第二个参数表示截取的长度。slice() 和substring()区别就是在参数为负,slice是都加上字符串长度,得出新值,substring()都变为0。substr()第二个参数为负,也转为0,第一个参数是直接加上字符串长度。

4.位置方法:

indexOf()、lastIndex() 就是查找位置,和数组一样

5.trim() 去掉字符串前后空白,兼容IE9+,因此自己写一个兼容方法

String.prototype.trim = function () {
    return this.replace(/(^\s*)|(\s*$)/g, '');
}

如果是jquery 直接 $.trim(str)就可以去掉前后空格

6.大小写转换

toLowerCase() toUpperCase()  toLocaleLowerCase() toLocaleUpperCase()

7.match() search() replace() split()

8.数组比较localeCompare() 

var stringValue = "yellow"; 
alert(stringValue.localeCompare("brick")); //1 
9.fromCharCode() 就是把字符编码变成对应的字符


猜你喜欢

转载自blog.csdn.net/viewyu12345/article/details/79413923