js原型獲取字串中特定字元的下標
阿新 • • 發佈:2019-01-29
RegExp.prototype.getIndex = function(str){
var vArray = str.match(this);
var indexArray = [];
if(vArray!= null){
for(var i =0,iLength=vArray.length;i<iLength;i++){
var vIndex = str.indexOf(vArray[i]);
if(vIndex>=0){
indexArray.push(vIndex);
}
}
}else{
return indexArray;
}
return indexArray;
};
var pattern = new RegExp("[*]+","g");
var vStr = "abcd*ef**ghi";
var vtt = pattern.getIndex(vStr);
if(vtt.length==0){
document.write("該字元中沒有匹配項!");
}else{
document.write("該字元中匹配到的字元下標為:"+vtt);
}