javascript profanity filter error - javascript

I have this code here:
var regex = /smell(y)?|poo/ig; //Banned Words
function countInArray(array, what) {
var count = 0;
for (var i = 0; i < array.length; i++) {
if (array[i] === what) {
count++;
}
}
return count;
}
function profanity() {
var array = [];
$('font').each( function() {
var string = $(this).html();
var pos = countInArray(array, $(this));
array.push($(this));
var updatedString = string.replace( regex, function(s) {
var i = 0;
var asterisks = "<span title='Blocked Word/Phrase!\nBlocked By Profanity Filter'>";
while (i < s.length) {
asterisks += "*";
i++;
}
asterisks = asterisks.concat("</span>");
$('font').html(asterisks)[pos];
});
});
}
The code basically scans through each font element for the banned words, however I cannot get it to replace the text for that element only all elements or none at all, I have tried to make an array which will add the value then scan for how many times it is there to try and get it but I am still having problems, can anyone help. I have searched everywhere, but I cannot find or replicate my problem anywhere. Can anyone help me, any help would be appreciated. Thanks!

Related

Use a loop for slicing

I'm trying to make a program where if you write in a word, let's say "Hello". And then you press the print button the outcome would be this:
"H"
"He"
"Hel"
"Hell"
"Hello".
Should i use a loop for this? My code so far is this:
function printit()
{
var temptext = document.getElementById("mytext").value;
temptext = temptext.slice(1,2);
document.getElementById("translated").innerHTML=temptext;
}
Anyone got any suggestions on how to solve this?
Here's how this would work with a loop.
Loop over the characters
Use the loop counter (i) to progressively slice the required chunk off your text.
Make sure you slice(0, i + 1), so you don't slice(0, 0) on the 1st iteration
function print() {
var text = document.querySelector("#text").value
for(var i = 0; i < text.length; i++) {
console.log(text.slice(0, i + 1))
}
}
<input id="text" value="Hello"/>
<button onclick="print()">Print</button>
You can use .map() with a scoped variable, to return an array of the words you need
function toSplicedWordArray(what) {
var before='';
return what.split('').map(function(item) {before+=item;return before;});
}
console.log(toSplicedWordArray('hello'));
try this:
let word = 'Good';
for (let i = 1; i <= word.length; i++) {
console.log(word.substring(0, i));
}
function printinit() {
var tempText = document.getElementById("mytext").value;
var slicedText = "";
for (var i = 0; i < tempText.length; i++) {
slicedText = tempText.slice(0, i) + " ";
}
document.getElementById("translated").innerHTML = temptext;
}

Calculate sentences using function in Javascript

I have come across a question about calculating sentences using a form in HTML, but I wanted to work out the function first to see if it would work. Here is my function that I have not been able to get it working in jsfiddle (https://jsfiddle.net/jdloomis/fxt81ynu/2/):
var numSentences = 0;
function calSentences(longString) {
var length = longString.length;
var sentence = '';
for (var i = 0; i < length; i++) {
sentence += longString[i];
if (longString[i] == '.') {
numSentences++;
sentence = '';
}
}
}
console.log(calSentences("This is a sentence. My second sentence."));
I have been able to figure out most of the functions and what they do in my book except this one and a word count without using .split, I will post that one in another post if I cannot figure it out.
You were so close with your attempt! All you forgot to do is return the number of sentences with return numSentences:
var numSentences = 0;
function calSentences(longString) {
var length = longString.length;
var sentence = '';
for (var i = 0; i < length; i++) {
sentence += longString[i];
if (longString[i] == '.') {
numSentences++;
sentence = '';
}
}
return numSentences;
}
console.log(calSentences("This is a sentence. My second sentence."));
Hope this helps! :)
Your code is correct, but you are not returning anything from your function.
Also, keep var numSentences local to your function, so that it's reset to 0 each time you run your function. Otherwise, you are adding on to the previous calculation each time you run the function.
function calSentences(longString) {
var numSentences = 0;
var length = longString.length;
var sentence = '';
for (var i = 0; i < length; i++) {
sentence += longString[i];
if (longString[i] == '.') {
numSentences++;
sentence = '';
}
}
return numSentences;
}
console.log(calSentences("This is a sentence. My second sentence."));

Removing Duplicate Items in an Array without Regex or filter

I have been stumped on this problem for a few hours now and am making no progress. I feel like this should be simple. I am trying to Remove duplicate characters in a String without using methods such as Filter or a Reg ex.
Here is my current code:
var duplicate = function(string) {
var newString = string.split("");
var finalArrayWithNoDuplicates = []
for (var i = 0; i < newString.length; i++){
for (var=0; j < newString.length; i++){
while(newString[i])
if (newString[i] !== newString[j]){
}
}
}
return finalArrayWithNoDuplicates.join("");
};
I am able to filter one letter at a time but as I progress down the chain in the while statement I am adding letters that were filtered out originally.
All of the algorithm tutorials for this algorithm are in Java that I have been finding. Is there a way to do this with only using a a for and while loops?
There are several things wrong with the proposed code:
It has serious errors (the inner loop is written all wrong)
You don't need to involve arrays at all, strings will do just fine
The "if char !== other char" check will never provide enough information to act on
Here's an alternative version using for loops and the same basic idea:
function deduplicate(str) {
var result = "";
for (var i = 0; i < str.length; ++i) {
var found = false;
for (var j = 0; j < i; ++j) {
if (str[i] == str[j]) {
found = true;
break;
}
}
if (!found) result += str[i];
}
return result;
}
Each character str[i] in the input string is compared to all characters str[j] that precede it (there is no point in comparing to characters that follow it because we are going to process those when their turn comes up anyway). If the character is not equal to any of those that precede it then we know it's the first of its kind to appear and include it in the result.
Note that this algorithm has O(n²) performance, which is very poor compared to other possible approaches. Its main selling point is that it is straightforward and that everything happens "in front of your eyes".
Here is a slightly modified version of your function that uses an object to keep track of which letters have already been encountered:
var duplicate = function(string) {
var finalArrayWithNoDuplicates = [];
var seen = {};
for (var i = 0; i < string.length; i++) {
if (!seen[string[i]]) {
finalArrayWithNoDuplicates.push(string[i]);
seen[string[i]] = 1;
}
}
return finalArrayWithNoDuplicates.join("");
};
No need for two nested for-loops
No need for "while" loop as well
in the following line of code there are two errors: for (var=0; j < newString.length; i++){ first one is var=0 (compilation error) and second is theat you increment i instead of j
It can be done by adding only unique elements (that don't appear twice) to finalArrayWithNoDuplicates
as follows:
var duplicate = function(newString) {
var finalArrayWithNoDuplicates = []
var x = 0;
for (var i = 0; i < newString.length; i++){
// if the char appears in another index
// or if it's already in the result - don't add it
if (newString.lastIndexOf(newString[i]) !== i || finalArrayWithNoDuplicates.indexOf(newString[i]) > -1){
continue;
}
else{
finalArrayWithNoDuplicates[x++] = newString[i];
}
}
return finalArrayWithNoDuplicates.join("");
};
var arr = [1,2,3,4,5,4,5,6,7];
alert(duplicate(arr));
OUTPUT:
1234567

Dividing words from text starting with a certain character

I want to test each word from a text if it starts with the character # if it does, i will put the word in variable 'response' if not, i will continue searching.
I tried something like :
var found = false;
for (i = 0; i < text.length; i++) {
if (found = /^#...$/.test(text[i])) {
found = true;
}
if (found== true){
//other stuff
}
}
could you help me with this one ?
You can use split on space, and then use substring to find the first letter. Then compare it.
Demo
var arr= text.split(' ');
for (i = 0; i < arr.length; i++) {
if (arr[i].substring(0,1) == '#') {
console.log('found!: ' + arr[i]);
break;
}
}
You probably want something like:
var found = false, response;
for (i = 0; i < text.length; i++) {
if (/^#.*$/.test(text[i])) {
found = true;
response = text[i];
break;
}
}
That matches everything that starts with a #. If you just want to match non-space characters, use the RegEx /^#(\S)*$/

Looping through arrays to check for patterns

I'm trying to loop through an array to check for a specific pattern but keep getting no output afterwards. Not sure what I've done wrong! I would appreciate any help!
I am testing for the pattern at or hat.
sample = ["cat fat hat mat", "that the who"]
searchTerm = prompt("Testing?");
function count(sample, searchTerm)
{
for (i=0;i<sample.length;i++)
{
if (sample[i].indexOf(searchTerm) == -1)
{
return 0;
}
return count(sample.substring(sample.indexOf(searchTerm) + searchTerm.length), searchTerm) + 1;
}
}
alert(count(sample, searchTerm));
Rehashed code
search = ["cat fat hat mat", "that the who"];
var pattern = prompt('Search?');
function count(sample, searchTerm)
{
var count, i;
count = 0;
for (i=0; i < sample.length; i++)
{
if (sample[i].indexOf(searchTerm) !== -1)
{
count++;
}
}
return count;
}
count(search, pattern);
I've redone everything and it still gives no output.
There are a couple of problems with this code. The most immediate one is you are calling substring on an array and not a string.
return count(sample.substring ...
Likely you meant to say
return count(sample[i].substring ...
The second issue though is that you need to divide the logic up a bit. You need to divide it up into sections that count the occurrences in a word and that which iterates through the array. Today they are intertwined and results in odd behavior because you end up passing non-arrays to places expecting arrays
function count(sample, searchTerm) {
var num = 0;
for (i=0;i<sample.length;i++) {
var current = sample[i];
var index = current.indexOf(searchTerm);
while (index >= 0) {
num++;
index = current.indexOf(searchTerm, index + 1);
}
}
return num;
}
Working Fiddle: http://jsfiddle.net/wrNbL/
You don't need to use recursion here, just iterate through the array once counting if the search term matches.
function count(sample, searchTerm)
{
var count, i;
count = 0;
for (i=0; i < sample.length; i++)
{
if (sample[i].indexOf(searchTerm) !== -1)
{
count++;
}
}
return count;
}

Categories