js最實用string(字符串)類型的使用及截取與拼接詳解


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


一、通過字符獲取位置或通過位置獲取字符:

//指定位置返回字符
console.log(str.charAt(1));
console.log(str[1]);
//指定位置返回字符編碼console.log(str.charCodeAt(1)); 
//返回字符串位置console.log(str.indexOf("o"));
//不存在返回-1console.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使用截取與拼接詳解整合,希望對大家有所幫助


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM