js最实用string(字符串)类型的使用及截取与拼接详解

var a = '世界上最远的距离不是天涯海角';

一、通过字符获取位置或通过位置获取字符:

//指定位置返回字符
console.log(str.charAt(1));
console.log(str[1]);
//指定位置返回字符编码
console.log(str.charCodeAt(1));
 
//返回字符串位置
console.log(str.indexOf("o"));//不存在返回-1
console.log(str.lastIndexOf("o"));

在浏览器中执行结果如下:

假如现在有个变量:

var a = '世界上最远的距离不是天涯海角';

var b = '最远的距离';

现在想动态获取到变量b之前的字符串,和变量之后的字符串,则可以这样

1.利用slice获取到之前的字符串;

2.获取到变量b的长度,在b初始位置后加上b的长度,及从b的尾部截取a的长度(当然a当长度可以省略!);

二、拼接字符串:

一般有两种:

a.直接用“+”;

b.concat函数

三、切割方法

console.log(str.slice(3,7));//开始、结束(有开始、有结束)
console.log(str.substring(3,7));//开始、结束(有开始、有结束)
console.log(str.substr(3,7));//开始、长度(有开始、无结束、有长度)
 
console.log(str.slice(-3,-2));//第一个负值与长度相加,第二个负值与长度相加
console.log(str.substring(3,-1));//第一个负值转换为0,第二个负值转换为0,如果开始大于结束,则对调
console.log(str.substr(-3,-1));//第一个负值与长度相加,第二个负值转换为0

下面看个例子:

var type可为dir/file

if (type !== 'dir' && name.indexOf('.') !== -1) {//file
 basename=name.substr(0,name.lastIndexOf('.'));
 extension=name.substr(name.lastIndexOf('.'));
} else {//dir
 basename=name;
 extension=false;
}


//中文


四、去掉前后空格

var strValue = " hello world! ";
var trimedStrValue = strValue.trim();
console.log(strValue);
console.log(trimedStrValue);

五、大小写转换方法

var strLowUp = "HELLO world!";
console.log(str.toLowerCase());
console.log(str.toUpperCase());
console.log(strLowUp);

六、与模式有关的方法,调用者为字符串,参数为模式(正则对象或正则表达式或字符串)

1、匹配方法,本质上与调用RegExp的exec()方法相同(调用者为正则表达式或正则对象,参数为字符串)
 //返回数组对象,第一项为匹配到的字符串,其它项为捕获组匹配到的字符串
//返回对象同时具有index和input属性,index为匹配到字符串的索引,input为进行匹配的字符串str

 2、查询/搜索方法
 //返回值为匹配字符的索引,如未查询到则返回-1

 search() 方法用于检索字符串中指定的子字符串,或检索与正则表达式相匹配的子字符串。

3、替换方法,两个参数,用参数二替换参数一,参数一为字符串或正则表达式,参数二为字符串或函数

a. //正则

b. 字符串

c. 函数

//如果第二个参数是函数
//函数接收的参数为:匹配到的子字符串、
  第一个捕获组匹配到的子字符串、
  第二个捕获组匹配到的子字符串...、模式匹配项的索引、原始字符串
var repStr = str.replace(/at/g,function(match,index,input){
console.log(match);//at
console.log(index);//
console.log(input);//cat,bat,sat,fat
return "an";
});
 
console.log(repStr);//can,ban,san,fan

4、分割方法,将字符串按照指定的分隔符分割为多个子字符串

 
//返回值为存放多个子字符串的数组
var str = "red,blue,green,yellow";
var strArray = str.split(",");
var strArray = str.split(/[^,]+/);//匹配所有不是逗号字符作为分隔符
console.log(strArray);//["red", "blue", "green", "yellow"]
 
//第二个参数用于控制数组的长度
var strArray = str.split(",",2);
console.log(strArray);//["red", "blue", "green", "yellow"]

七、比较方法,返回值为1(>0)、0、-1(<0)

var strValue = "yellow";
console.log(strValue.localeCompare("brick"));//>0
console.log(strValue.localeCompare("yellow"));//0
console.log(strValue.localeCompare("zoo"));//<0

以上所述是小编给大家介绍的js string使用截取与拼接详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对来客网网站的支持!