码迷,mamicode.com
首页 > 编程语言 > 详细

JavaScript常用字符串方法

时间:2015-01-25 16:25:10      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:

1.substr
substr() 方法可从字符串中截取从指定下标开始的指定数目的字符
stringObject.substr(start, length)
start:要截取的子字符串的起始下标(可以为负数,-1表示最后一个字符)
length:子串中的字符串长度(如果没有指定 length,那么返回的字符串包含从 start 到 stringObject 的结尾的字符)
var str = ‘Front End Engineer‘;
str.substr(6, 3)); // End
str.substr(6)); // End Engineer
 
2.substring
substring() 方法用于截取字符串中位于两个指定下标之间的字符
stringObject.substring(start, stop)
start:一个非负的整数,规定要提取的子字符串的第一个字符在 stringObject 中的位置
stop:一个非负的整数,比要提取的子串的最后一个字符在 stringObject 中的位置多 1(因为截取的时候不包括stop下标对应的字符)。(如果省略该参数,那么返回的是从start位置一直截取到字符串的最后的子字符串。)
var str = ‘Hello World‘;
str.substring(6, 11)); // World
str.substring(2)); // llo World

 

3.toUpperCase, toLowerCase
toUpperCase() 方法用于把字符串转换为大写
toLowerCase() 方法用于把字符串转换为小写 
var str = ‘Hello World‘;
str.toUpperCase(); // HELLO WORLD
str.toLowerCase(); // hello world

 

4.split
split() 方法用于把一个字符串分割成字符串数组。
stringObject.split(separator, howmany)
separator:字符串或正则表达式,用来分割字符串的标志(如果separator为空字符串 (""),那么 stringObject 中的每个字符之间都会被分割);
howmany:可选参数,指定返回的数组的最大长度
var str1 = ‘hello‘;
str1.split(‘‘); // ["h", "e", "l", "l", "o"]
 
var str2 = ‘2014-12-20‘
str2.split(‘-‘); // ["2014", "12", "20"]
 
var str3 = "What‘s your name?";
str3.split(‘ ‘); // ["What‘s", "your", "name?"]
str3.split(/\s+/); // ["What‘s", "your", "name?"]
str3.split(‘ ‘, 2); // ["What‘s", "your"]

 

5.indexof
indexOf() 方法返回某个指定的字符串值在字符串中首次出现的位置
stringObject.indexOf(searchvalue,fromindex)
searchvalue:需要检索的字符串值;
fromindex:可选的整数参数,规定在字符串中开始检索的位置,0 到 stringObject.length - 1。如省略该参数,则将从字符串的首字符开始检索。 
var str = ‘How do you do!‘
str.indexOf(‘u‘); // 9
str.indexOf(‘you‘); // 7
str.indexOf(‘you‘, 8); // -1
str.indexOf(‘how‘); // -1
str.indexOf(‘do‘); // 4

 

6.lastIndexOf
lastIndexOf() 方法返回某个指定的字符串值在字符串中最后出现的位置,在一个字符串中的指定位置从后向前搜索。
stringObject.lastIndexOf(searchvalue, fromindex)
searchvalue:需要检索的字符串值;
fromindex:可选的整数参数,规定在字符串中开始检索的位置,0 到 stringObject.length - 1。如省略该参数,则将从字符串的最后一个字符开始检索。
var str = ‘How do you do!‘;
str.lastIndexOf(‘u‘); // 9
str.lastIndexOf(‘you‘); // 7
str.lastIndexOf(‘you‘, 6); // -1
str.lastIndexOf(‘do‘); // 11
 
7.charAt
charAt() 方法返回指定位置的字符
stringObject.charAt(index) 
var str = ‘Front End‘;
str.charAt(2); // "o"

 

8.charCodeAt
charCodeAt() 方法返回指定位置的字符的 Unicode 编码(0 - 65535之间的整数) 。
stringObject.charCodeAt(index)
 
中文Unicode范围
一般:u4e00 - u9fa5
更广:u2e80 - ua4cf  ||   uf900 - ufaff || ufe30 - ufe4f
 
9.trim
trim() 方法可以用来去除字符串的首尾空格
stringObject.trim()
‘ hello  ‘.trim(); // "hello"
IE9以下的浏览器中不支持此方法,解决的方法有以下2种:
1.使用正则表达式:str.replace(/(^\s*)|(\s*$)/g, ‘‘);
2.使用jQuery的trim方法:$.trim(str)。
 
10.toFixed
toFixed() 方法可把 Number 四舍五入为指定小数位数的数字(位数需要在0到20之间)
NumberObject.toFixed(num)
var num = 12.236;
num.toFixed(2); // 12.24

 

JavaScript常用字符串方法

标签:

原文地址:http://www.cnblogs.com/happyfreelife/p/4248293.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!