過濾特別的字元,使用Regular Expression (RegExp) in JavaScript
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Regular Test</title>
<script type="text/javascript">
function filterChar(pNameStr,pReplaceStr){
// ======================================================================================='
// 功能說明: 過濾特別的字元,使用Regular Expression (RegExp) in JavaScript
// 預設改為字元為 "" 無字元
// 這些逃脫字元有: -[]/{}()*+=?.,\\^$|~#%&'"\!@;:<>_`
// 有過濾空白
// Regular code: /[\ \-\[\]\/\{\}\(\)\*\+\=\?\.\,\\\^\$\|\~\#\%\&\'\"\!\@\;\:\<\>\_\`]/g
// 傳入參數:
// pNameStr : 要過濾的來源字串'
// pReplaceStr : 要取代為什麼字元。
// 傳回參數:
// Error : Return false
// Success : Return 過濾完成的字串。
//
// 用法: filterChar("abc123 ~!@#$%^&*(){}[]`/=?+\|-_;:'\",<.> 123654"))
// filterChar("abc123 ~!@#$%^&*(){}[]`/=?+\|-_;:'\",<.> 123654","_"))
//
// Referring: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/regexp
//
// author levin
// 日期:2013/04/22
// ====================================================================================='
var specials = [
" "
, "-"
, "["
, "]"
, "/"
, "{"
, "}"
, "("
, ")"
, "*"
, "+"
, "="
, "?"
, "."
, ","
, "\\"
, "^"
, "$"
, "|"
, "~"
, "#"
, "%"
, "&"
, "'"
, "\""
, "!"
, "@"
, ";"
, ":"
, "<"
, ">"
, "_"
, "`"
];
var regex = RegExp('[' + specials.join('\\') + ']', 'g');
var replaceStr = "";
if(null != pReplaceStr){
replaceStr = pReplaceStr;
};
var str = pNameStr;
str = str.replace(regex,replaceStr);
return str;
}
</script>
</head>
<body>
<label for="name">測試過瀘的資料,輸入資料:</label>
<input name="replaceData" id="replaceData" type="text" value="" />
<button onclick="document.getElementById('return').innerHTML=filterChar(document.getElementById('replaceData').value)">過瀘</button>
<p id="return"></p>
</body>
</html>
Regular Test
其它文章
沒有留言:
張貼留言