专业编程基础技术教程

网站首页 > 基础教程 正文

互联网前端开发技术JavaScript字符串类型详解

ccvgpt 2024-07-19 12:49:54 基础教程 9 ℃

String类型

String类型包含了三个属性和大量的可用内置方法。

String对象属性

String也包含对象的通用方法,比如valueOf()、toLocaleString()和toString()方法,但这些方法都返回字符串的基本值。

互联网前端开发技术JavaScript字符串类型详解

字符方法

var box = 'Mr.Lee'; 
alert(box.charAt(1));//r 
alert(box.charCodeAt(1));//114 
alert(box[1]);//r,通过数组方式截取 

PS:box[1]在IE浏览器会显示undefined,所以使用时要慎重。

字符串操作方法

var box = 'Mr.Lee';
alert(box.concat(' is ', ' Teacher ', '!'));//Mr.Lee is Teacher ! 
alert(box.slice(3));//Lee 
alert(box.slice(3,5));//Le 
alert(box.substring(3));//Lee 
alert(box.substring(3,5));//Le 
alert(box.substr(3));//Lee 
alert(box.substr(3,5));//Lee 
var box = 'Mr.Lee'; 
alert(box.slice(-3));//Lee,6+(-3)=3位开始 
alert(box.substring(-3));//Mr.Lee 负数返回全部 
alert(box.substr(-3));//Lee,6+(-3)=3位开始
var box = 'Mr.Lee'; 
alert(box.slice(3, -1));//Le 6+(-1)=5, (3,5) 
alert(box.substring(3, -1));//Mr.第二参为负,直接转0,并且方法会把较小的数字提前,(0,3) 
alert(box.substr(3, -1));//'' 第二参数为负,直接转0 ,(3,0) 

PS:IE的JavaScript实现在处理向substr()方法传递负值的情况下存在问题,它会返回原始字符串,使用时要切记。

字符串位置方法

var box = 'Mr.Lee is Lee'; 
alert(box.indexOf('L'));//3 
alert(box.indexOf('L', 5));//10 
alert(box.lastIndexOf('L'));//10 
alert(box.lastIndexOf('L', 5));//3,从指定的位置向前搜索 

PS:如果没有找到想要的字符串,则返回-1。

示例:找出全部的L

var box = 'Mr.Lee is Lee';//包含两个L的字符串 
var boxarr = [];//存放L位置的数组 
var pos = box.indexOf('L');//先获取第一个L的位置 
while (pos > -1) {//如果位置大于-1,说明还存在L 
 boxarr.push(pos);//添加到数组 
 pos = box.indexOf('L', pos + 1);//从新赋值pos目前的位置 
} 
alert(boxarr);//输出 

大小写转换方法

var box = 'Mr.Lee is Lee'; 
alert(box.toLowerCase());//全部小写 
alert(box.toUpperCase());//全部大写 
alert(box.toLocaleLowerCase());// 
alert(box.toLocaleUpperCase());//

PS:只有几种语言(如土耳其语)具有地方特有的大小写本地性,一般来说,是否本地化效果都是一致的。

字符串的模式匹配方法

正则表达式在字符串中的应用,在前面的章节已经详细探讨过,这里就不再赘述了。 以上中match()、replace()、serach()、split()在普通字符串中也可以使用。

var box = 'Mr.Lee is Lee'; 
alert(box.match('L'));//找到L,返回L否则返回null 
alert(box.search('L'));//找到L的位置,和indexOf类型 
alert(box.replace('L', 'Q'));//把L替换成Q 
alert(box.split(' '));//以空格分割成字符串 

其他方法

alert(String.fromCharCode(76)); //L,输出Ascii码对应值

localeCompare(str1,str2)方法详解:

? 比较两个字符串并返回以下值中的一个;

? 如果字符串在字母表中应该排在字符串参数之前,则返回一个负数。(多数-1)

? 如果字符串等于字符串参数,则返回0。

? 如果字符串在自附表中应该排在字符串参数之后,则返回一个正数。(多数1)

var box = 'Lee'; 
alert(box.localeCompare('apple'));//1 
alert(box.localeCompare('Lee'));//0 
alert(box.localeCompare('zoo'));//-1 

【扩展】

以上是通过JS生成一个html标签,根据经验,没什么太大用处,做个了解。

var box = 'Lee'; // 
alert(box.link('http://www.yc60.com')); //超链接

总结

通过本篇文章,你可以学到以下知识点:

1.字符串的对象属性;

2.字符串方法;

3.字符串操作方法;

4.字符串位置方法;

5.字符串的模式匹配;

6.其他方法;

IT技术研习社,专注互联网技术研究与分享,喜欢的朋友可以点击【关注】;把经验传递给有梦想的人;

Tags:

最近发表
标签列表