js中的String对象操作

//length 属性返回字符串的长度(字符数)
var str = "hello world";
 console.log(str.length);
//indexOf()	返回指定字符在字符串中首次出现的位置
var url = 'http://127.0.0.1:3000/api/hook/list/308.shtml';//实现取得308
console.log(url.indexOf('/')); 
//lastIndexOf() 返回指定字符在字符串中最后出现的位置
var url = 'http://127.0.0.1:3000/api/hook/list/308.shtml';//实现取得308
console.log(url.lastIndexOf('/')); //35
console.log(url.lastIndexOf('.')); //39
console.log(url.substring(url.lastIndexOf('/')+1,url.lastIndexOf('.'))); //308
//string.substr(start[,length]) 返回从start位置开始截取length长度的字符串,如果length省略,则截取到最后,如果start为负数,则是从最后数起
var str="Hello world!";
console.log(str.substr(2)); //llo world!
console.log(str.substr(2,6)); //llo wo
console.log(str.substr(-2)); //d!
console.log(str.substr(-2,1)); //d
console.log(str.substr(-2,2)); //d!
//string.substring(start[,end]) 返回从start位置开始到end位置结束的字符,包括start位置的字符,但不包括end位置的字符,start与end要求为非负整数,
//如果end大于字符串最后一个字符的位置,则会忽略end参数
var name = 'jiangzunshao';
console.log(name.substring(1)); //iangzunshao 说明:省略end,截取到最后
console.log(name.substring(1,2)); //i 说明:包括start位置的字符,但不包括end位置的字符
console.log(name.substring(1,20)); //iangzunshao 说明:end大于字符串最后一个字符的位置,则忽略end参数
//string.replace(search,new) 在字符串中查找search匹配的子串,使用new替换与search匹配的子串
var str="Mr Blue has a blue house and a blue car";
console.log(str.replace(/blue/,"red")); //Mr Blue has a red house and a blue car
console.log(str.replace(/blue/g,"red")); //Mr Blue has a red house and a red car 说明:g全局匹配,并替换
console.log(str.replace(/blue/gi,"red")); //Mr red has a red house and a red car 说明:g全局匹配,i忽略大小写
//string.toLowerCase() 把字符串转换为小写
var email = "[email protected]";
console.log(email.toLowerCase()); //[email protected]
//toUpperCase()	把字符串转换为大写
console.log(email.toUpperCase()); //[email protected]
// charAt()	返回在指定位置的字符
var str = "HELLO WORLD";
console.log(str.charAt(2)); //L
// charCodeAt()	返回在指定的位置的字符的 Unicode 编码
console.log(str.charCodeAt(2)); //76
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章