Javascript正則匹配檔名和檔案字尾
阿新 • • 發佈:2018-12-17
//去除字串前後空格 String.prototype.trim = function() { return this.replace(/(^\s+)|(\s+$)/g, ''); }; //11位手機號格式化 function telFormat(tel, space) { space = space ? space : ' '; return String(tel).replace(/(\d{3})(\d{4})(\d{3})/, '$1' + space + '$2' + space + '$3'); } //獲取路徑檔案資訊(檔名、字尾名) /*var path = "C:\\Users\\sungang\\Desktop\\temp\\email\\index.html"; var href = window.location.href; var url = 'https://www.example.com/search/LM358.html?type=1&num=1';*/ function getFileInfo(filePath, key) { filePath = filePath.split('?')[0]; //去引數 var re = /([^\.\/\\]+)\.([a-z]+)$/i, resultArr = re.exec(filePath), info = {}; if (resultArr) { info.name = resultArr[1]; info.type = resultArr[2]; } return key ? info[key] : info; } /*console.log(getFileInfo(path)); console.log(getFileInfo(href)); console.log(getFileInfo(url)); console.log(getFileInfo(url, 'type'));*/ //獲取連結字串引數 function getParams(path) { var obj = {}; path = path ? path : window.location.href; //[^\?&=]+ 表示不含?或&或=的連續字元,加上()就是提取對應字串 path.replace(/([^\?&=]+)=([^\?&=]*)/gi, function(rs, $1, $2, offset, source) { obj[$1] = $2; }) return obj; }