In a previous question I asked how to implement a client side bad word filter.
The problem I have is that I don’t want to send the masive string to the page, but rather call it from an external file.
here’s the code so far
var filter = ['ass']; // this is a literal JSON result
String.prototype.repeat = function (num) {
return new Array(num + 1).join(this);
}
$('body').html(function (i, txt) {
for (var i = 0; i < filter.length; i++) {
// Create a regular expression and make it global
var pattern = new RegExp('\\b' + filter[i] + '\\b', 'g');
txt = txt.replace(pattern, "****");
}
return txt;
});
But I’d like to change it to soemthing like
var filter = '/generic/profanity/'; // the "profanity" page generates the exact
// same JSON result as above only in a cached
// external page (it's actually generated by
// an ASP.NET MVC Controller (ContentResult)
String.prototype.repeat = function (num) {
return new Array(num + 1).join(this);
}
$('body').html(function (i, txt) {
for (var i = 0; i < filter.length; i++) {
// Create a regular expression and make it global
var pattern = new RegExp('\\b' + filter[i] + '\\b', 'g');
txt = txt.replace(pattern, "****");
}
return txt;
});
but unfortunately with this, it’s using '/generic/profanity' as a literal string for the regex rather than a reference path.
This is probably something really stupid, but how would I fix this?
Edit:
after @GSP’s answer I’m trying this approach, and though it feels closer, it’s still not working.
If I go into firebug and look at the “filter” variable in the DOM, it is represented as ['asdf']
var filter = '';
String.prototype.repeat = function (num) {
return new Array(num + 1).join(this);
}
$('.page').html(function (i, txt) {
$.getJSON('/generic/profanity', function (data) {
// data is the contents of the
filter = data;
});
for (var i = 0; i < filter.length; i++) {
// Create a regular expression and make it global
var pattern = new RegExp('\\b' + filter[i] + '\\b', 'g');
txt = txt.replace(pattern, "****");
}
return txt;
});
Because the JQuery will always be run from the browser context you will always be downloading the file anyway so this isn’t going to work the way you think it is.
But, if you want to use this method you’ll want to use one of the JQuery methods like $.get, or $.getJSON to get the file from your server before you parse it: