JavaScript Tutorial/Regular Expressions/Filter
Содержание
Bad word filter
<source lang="javascript">
<html> <head>
<title>Bad Words Example</title> <script type="text/javascript"> function filterText(sText) { var reBadWords = /badword|anotherbadword/gi; return sText.replace(reBadWords, "****"); } function showText() { var oInput1 = document.getElementById("txt1"); var oInput2 = document.getElementById("txt2"); oInput2.value = filterText(oInput1.value); } </script>
</head> <body>
<textarea rows="10" cols="50" id="txt1">badword anotherbadword</textarea>
<input type="button" value="Filter Bad Words" onclick="showText()" />
Filtered Text:
<textarea rows="10" cols="50" id="txt2"></textarea>
</body> </html></source>
Strip HTML
<source lang="javascript">
<html> <head> <title>Strip HTML Example</title> <script type="text/javascript">
String.prototype.stripHTML = function () { var reTag = /<(?:.|\s)*?>/g; return this.replace(reTag, ""); }; function showText() { var oInput1 = document.getElementById("txt1"); var oInput2 = document.getElementById("txt2"); oInput2.value = oInput1.value.stripHTML(); }
</script>
</head>
<body>
<textarea rows="10" cols="50" id="txt1"></textarea>
<input type="button" value="Strip HTML" onclick="showText()" /></p>
Stripped Text:
<textarea rows="10" cols="50" id="txt2"></textarea>
</body> </html></source>
Trim the leading and trailing spaces
<source lang="javascript">
<html> <head> <title>Trim Example</title> <script type="text/javascript">
String.prototype.trim = function () { var reExtraSpace = /^\s+(.*?)\s+$/; return this.replace(reExtraSpace, "$1"); };
function showText() { var oInput1 = document.getElementById("txt1"); var oInput2 = document.getElementById("txt2"); oInput2.value = oInput1.value.trim(); }
</script>
</head>
<body>
<textarea rows="10" cols="50" id="txt1"></textarea>
<input type="button" value="Trim" onclick="showText()" /></p>
Trimmed Text:
<textarea rows="10" cols="50" id="txt2"></textarea>
</body> </html></source>
Use regular expression to remove bad words
<source lang="javascript">
<html> <head> <title>Bad Words Example</title> <script type="text/javascript">
function filterText(sText) { var reBadWords = /badword|anotherbadword/gi; return sText.replace(reBadWords, function (sMatch) { return sMatch.replace(/./g, "*"); }); } function showText() { var oInput1 = document.getElementById("txt1"); var oInput2 = document.getElementById("txt2"); oInput2.value = filterText(oInput1.value); }
</script> </head> <body>
<textarea rows="10" cols="50" id="txt1">badword anotherbadword</textarea>
<input type="button" value="Filter Bad Words" onclick="showText()" /></p>
Filtered Text:
<textarea rows="10" cols="50" id="txt2"></textarea>
</body> </html></source>