JS中string字符串的方法

2019-10-10  本文已影响0人  拾柒_aab0

方法

toLocaleString()、toString和valueof()方法,都返回对象所表示的基本字符串值。
String有length属性,表示字符串中包含了多少了字符。

例:

var str = "hello world";
console.log(str.length); 

charAt()方法

传入下标返回给定位置的项

var str = 'hello world';
console.log(str.charAt(3));//l

charCodeAt()方法

传入下标返回给定位置的项所的代表的编码

ascll码表

QQ截图20170119114831.png
var str = 'hello world';
console.log(str.charCodeAt(3));//101

fromCharCode()方法

传入编码返回字符

var str = 'hello world';
console.log(String.fromCharCode(104, 101, 108, 108, 111)); //hello

字符串操作方法

concat()拼接字符串

 var str = 'hello world';
console.log(str.concat('uuuu'))// hello world uuuu

ES还提供了三个基于子字符串创建新字符串的方法:
slice()、substr() 和 substring()
slice()和substring()第一个参数是起始下标,第二个参数终止下标;
但是当substring()遇见负数的适合会把负数转化为0,会把大的下标放在前面
而substr()的第二个参数指的是返回的字符的个数。如果没有给这些方法传第二个参数,则将字符串的末尾作为结束位置。这三个方法都不会修改字符串本身(子字符串)。

 console.log(str.substring(1,3));//el
 console.log(str.slice(2,5));//llo
 console.log(str.substring(1, -3));//h
 console.log(str.slice(2, -3));//llo wo
 console.log(str.substr(1,3));//ell

字符串位置方法

indexof()
lastIndexof()
例:
var str = "hello world";
console.log(str.indexof("o")); //4
console.log(str.lastIndexof("o")); //7
console.log(str.indexof("o",6)); //7
console.log(str.lastIndexof("o",6)); //4
如果检测不到返回-1

trim()方法会删除字符串前置或后缀的空格

var str = "    hello world    ";
    console.log(str.trim());//hello world

replace()方法替换

var str = 'hello world';
console.log(str.replace('l','8'));//he8lo world

如果想要替换所有的项要用到正则的方法
var bb = 'hkkkkhhhhll';
console.log(bb.replace(/\h/g, '9'));//9kkkk9999ll

字符串大小写转换方法

toLowerCase() 转小写
toLocaleLowerCase() 根据特定地区的语言转小写
toUpperCase() 转大写
toLocaleUpperCase() 根据特定地区转大写

例:
var str = "hello world";
console.log(str.toUpperCase());    //"HELLO WORLD"
console.log(str.toLocaleUpperCase());  //"HELLO WORLD"
console.log(str.toLowerCase());   //"hello world"
console.log(str.toLocaleLowerCase());  //"hello world"
上一篇下一篇

猜你喜欢

热点阅读