我正在制作一个简单的socket.io应用程序,您可以在https://backchannel.glitch.me上看到它。我正在尝试使用RegExp为此站点添加一个相对简单的亵渎过滤器,但是我一直遇到问题-当检测到不良单词时,没有显示我想要的消息,什么也没有发生。我对JS和正则表达式缺乏经验,因此可能有些地方被我我忽略了,我将不胜感激。
我的代码:
<!doctype html>
<html>
<head>
<script>
if (location.protocol != 'https:') {
location.href = 'https://backchannel.glitch.me'
}
</script>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" type="image/x-icon" href="https://cdn.glitch.com/a359ff0b-1273-40ab-a005-10968e106f1d%2Fimg_54456.png?1544043684904"/>
<title>Backchannel</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font: 13px Helvetica, Arial; text-align: left; overflow: auto; color: White;}
form { background: #666666; padding: 3px; position: static; bottom: 0; width: 100%; }
form input { padding: 8px; width: 90%; margin-right: .5%;}
form button { width: 9%; background: White; border: none; padding: 9px 8px; }
#messages { list-style-type: none; margin: 0; padding: 0; max-height: 95.7vh; overflow:}
#messages li { padding: 5px 10px; background: none;}
#messages li:nth-child(odd) { background: none; }
main {text-align: center; margin: 0; }
.messageContainer {overflow: auto;}
</style>
<head>
</head>
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var audio = new Audio('https://cdn.glitch.com/a359ff0b-1273-40ab-a005-10968e106f1d%2FError-sound.mp3?1544050723783');
$(function () {
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
//if a user types a message containing a "bad word", do not print it and instead print a system message saying it was blocked.
if (msg == new RegExp('*bad words*')) {
$('#messages').append($('<li>').text('[SYSMOD]: Message blocked due to explicit content'));
}
else
$('#messages').append($('<li>').text(' [USER]: ' + msg));
audio.play();
});
//When the server emits " new user connected", add a message which says so.
socket.on('new user', function(msg){
$('#messages').append($('<li>').text('[SYSTEM]: New User Connected'));
audio.play();
});
//When the server emits "user disconnected", add a message which says so.
socket.on('user disconnected', function(msg){
$('#messages').append($('<li>').text('[SYSTEM]: User Disconnected'));
audio.play();
});
});
</script>
<form action="">
<input id="m" autocomplete="off" /><button>Send Message</button>
</form>
</head>
<body background="https://cdn.glitch.com/a359ff0b-1273-40ab-a005-10968e106f1d%2Fspacewinter1.jpg?1545146217248">
<div id="main">
<div class="messageContainer">
<ul id="messages"></ul>
</div>
</div>
</body>
</html>
答案 0 :(得分:1)
将字符串与RegExp对象与布尔运算符进行比较将始终返回false。您要为此使用RegExp的test
方法。例如:
new RegExp("*bad words*").test(msg);
此外,还存在用于构造正则表达式的简写语法。
/myregex/.test(msg);