Append words from variable to words from another variable - javascript

I need to achieve something like the following code, where if a user entered for example (you are bad), it shows an alert. The below code isn't working because it alerts for the words (you are) only without reading what's in badAppend.
var badAppend= ["freak", "ugly", "bad"]
var badWords = [("you are"+badAppend)];
if((badWords)
{
alert("you cannot use this word/sentence");
return false;
}
I'm trying to ahcieve this to avoid doing like the following:
var badWords = ["you are bad", 'you are ugly", "you are freak"];
etc..
I'd really appreciate it much if anyone can help with this. regards.

A more vanilla JavaScript way, on this one you do a "blacklist" check first against an array of "Bad Words" printing only the sentences that are allowed:
var words = document.getElementById('userInput').value.split(" ");
var badWords = ['array', 'of', 'bad', 'words'];
for (i = 0; i < words.length; i++) {
for (ii = 0; ii < badWords.length; ii++) {
var exists = words.indexOf(badWords[ii]);
if (exists != -1) {
words.splice(exists, 1);
}
}
var result = document.getElementById('notInside');
result.innerHTML += words[i];
result.innerHTML += "</br>";
}
I know he's using jQuery but just as another example to do this for other people that might need it. If you need to only display words that ARE in the array just do:
var words = document.getElementById('userInput').value.split(" ");
var badWords = ['array', 'of', 'bad', 'words'];
for (ii = 0; ii < badWords.length; ii++) {
var exists = words.indexOf(badWords[ii]);
if (exists > -1) {
var result = document.getElementById('inside');
result.innerHTML += words[exists];
result.innerHTML += "</br>";
}
}

var newWords = $(badAppend).map(function(item) { return "you are " + item; });
This will give you
newWords = [ "you are freak", "you are ugly", "you are bad" ];

I would do something like this,
var match = $('div.text').text().match(/[yY]ou(('re)|(\sare))\s\w+/g);
if(match){
match = match.map(function(item){
return (item.substring(item.lastIndexOf(" ")+1)).toLowerCase();
});
var match2 = $(match).filter(badWordsArray);
if(match2.length > 0){
console.log('Bad word!');
}else{
console.log('Input is clean!');
}
}else{
console.log('Input is clean!');
}
Change the text selector in the first line to whatever you need.
This will go through all the text that user entered, matches all the words which were followed by one of these:
You are
You're
you are
You are
The match variable will be an array containing all those words, then you can filter it based on your bad word array to see if there was any bad word.
If there is non of those four "you are"s in the code it just logs the input is clean, otherwise it checks for bad words in lowercase.
If you are sure that you just need to match 'you are' exactly, you can replace the regex with this one, it will run faster too. /(you\sare)\s\w+/g

From what I understand, you have a dictionary of bad words and you are trying to prevent user from using those words. In that case, you can do the following:
var containsBadWords = function(words){
var badWords = ['bad', 'ugly', 'freak' /* ...*/];
var badWordCount = 0;
words.forEach(function(word){
if(badWords.indexOf(word)>-1) badWordCount++;
});
return badWordCount;
}
var userWords = 'i am bad you are bad';
var result = containsBadWords(userWords.split(' '));
if(result>0) alert();

Related

Why is my array 'undefined'? (vanilla javascript)

I'm trying to make a simple 'bad words' filter with javascript. It's meant to listen to any submit events on the page, then iterate through all input fields of the text type, check them for bad stuff by comparing the entered text with the word list, and finally return an according console.log/alert (for now).
I have two files: word-list.js with the critical words (loads first) and filter.js which pulls an array with all words from word-list.js.
My problems is, swear_words_arr[1] is 'undefined' and I don't understand why. I've been looking around for solutions, but still I can't seem to determine the reason for this. Help is much appreciated.
// get all inputs type = text and turn html collection into array
var getInputs = document.querySelectorAll("input[type=text]")
var inputs = Array.from(getInputs);
//var swear_alert_arr -> from in word-list.js
var swear_alert_arr = new Array();
var swear_alert_count = 0;
function reset_alert_count() {
swear_alert_count = 0;
}
function validate_text() {
reset_alert_count();
inputs.forEach(function(input) {
var compare_text = input.value;
console.log(compare_text);
for (var i = 0; i < swear_words_arr.length; i++) {
for (var j = 0; j < compare_text.length; i++) {
if (
swear_words_arr[i] ==
compare_text.substring(j, j + swear_words_arr[i].length).toLowerCase()
) {
swear_alert_arr[swear_alert_count] =
compare_text.substring(
j,
j + swear_words_arr[i].length
);
swear_alert_count++;
}
}
}
var alert_text = "";
for (var k = 1; k <= swear_alert_count; k++) {
alert_text += "\n" + "(" + k + ") " + swear_alert_arr[k - 1];
if (swear_alert_count > 0) {
alert("No!");
console.log('omg no bad stuff! D:');
} else {
console.log('no bad stuff found :)');
}
}
});
}
window.onload = reset_alert_count;
window.addEventListener('submit', function() {
validate_text();
});
It doesn't look like you've declared the array you're trying to access.
But, instead of loops with nested loops and keeping track of loop counters, just get a new array that contains any bad words in the submitted array. You can do this a number of ways, but the Array.prototype.filter() method works nicely:
let badWords = ["worse", "terrible", "horrible", "bad"];
let submittedWords = ["Good", "Terrible", "Great", "Fabulous", "Bad", "OK"];
// Loop over the submitted words and return an array of all the bad words found within it
let bad = submittedWords.filter(function(word){
// Do a case-insensitive match test. Return the word from the submitted words
// if it's on the bad word list.
return badWords.indexOf(word.toLowerCase()) > -1 ? word: null;
});
console.log("Bad words found in submitted data: " + bad.join(", "));

How to read line-by-line of a single parameter (input) from a JavaScript function?

I'm working on a Racker Rank problem whose function in JavaScript receives a single parameter (input).
Input Format:
The first line contains an integer, (the number of test cases).
Each line of the subsequent lines contain a String.
I need to print the even-indexed and odd-indexed characters of each string (S) separated by a space on a single line (see the Sample below for more detail).
2
Hacker
Rank
Hce akr
Rn ak
Is there a way to read the input line-by-line and save each string in a specific variable? If I achieve that I know how to solve the problem by iterating through the string. Otherwise, I'm lost. If not, how else could I handle the input? Thanks!
Readline doesn't seem to be the way to go.
function processData(input) {
//Enter your code here
}
process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
_input += input;
});
process.stdin.on("end", function () {
processData(_input);
});
What I have tried without success:
function processData(input) {
let myArray = input.split("\n");
let even_indexed = "";
let odd_indexed = "";
for (let i = 1; i <= myArray.length; i++) {
let str = myArray[i];
let len = str.length;
for (let j = 0; j < len; j++){
if (j % 2 == 0) { //check if the index is even;
even_indexed.concat(str[j]);
}
else {
odd_indexed.concat(str[j]);
}
}
}
console.log("%s %s", even_indexed, odd_indexed);
}
Can't you just use split() method with a newline operator?
<script>
let x= `Hey
I'm
a
multiline
string`
console.log(x.split("\n"))
</script>
The result will be an array on which every element represents a line of your input.
I made this pretty quickly so I apologize for it being kinda messy and I know there are probably more efficient ways of doing this, but it does what you are asking for.
let input = `This
is
a
multiline
string`
let splitWords = [];
input.split(/\r?\n/).forEach(function(e){ // Split the array by \n (newline) and/or \r (carriage return)
currentLine = {evenIndex: [], oddIndex: []}
for(let i = 0; i < e.length; i++){
if((i + 1)%2 === 0){
currentLine.evenIndex.push(e[i]);
}
else{
currentLine.oddIndex.push(e[i]);
}
}
splitWords.push(currentLine);
});
splitWords.forEach(function(e){
console.log(e.oddIndex.join('') + " " + e.evenIndex.join(''))
});

Compare strings in Javascript

I need to compare titles (which are made of many words)
with a list of bad words. For one word, indexOf works fine.
but when there are many swear words it doesn't.
Can anyone help with this?
var title = "This is my title";
var badwordlist = title.indexOf('fword and other bad words list');
//var badwordlist = title.indexOf('fword');
if ( badwordlist >= 0){
//do something
}
I feel the two answers posted so far are overdoing things
var title = "fword This is a f**king title.",
words = title.split(" "),
badwords = ["fword", "f**king"];
// one of these should do it
var isGood = words.filter(function(a) {
return badwords.indexOf(a) == -1;
});
var isBad = words.filter(function(a) {
return badwords.indexOf(a) != -1;
});
console.log(isBad, isGood);
// if isBad.length>0 then there were swear words in the title
You can use String.prototype.includes() to check if the string contains the bad word:
var title = "fword This is title.";
var badwords = ["fword", "f**k"];
var isbad = badwords.map(function(a) {
return title.includes(a);
});
console.log(isbad);
This is a simple solution, which involves an array, a cycle and a function which coordinates these
var badwords = ['fword', 'uglyword'];
var replacements = ['*word', 'ug***ord'];
function replaceBadwords(title) {
for (var badwordIndex in badwords) {
if (title.indexOf(badwords[badwordIndex]) >= 0) {
title = title.split(badwords[badwordIndex]).join(replacements[badwordIndex]);
}
}
}
However, the word 'assignment' contains an ugly word, which in fact is not ugly. I mean if you read only the first three characters, you will think this is an ugly word. To cope with these exceptions make sure you will not censor these as well.
See this SO question. This will do:
var arr = ['banana', 'monkey banana', 'apple', 'kiwi', 'orange'];
function checker(value) {
var prohibited = ['banana', 'apple'];
for (var i = 0; i < prohibited.length; i++) {
if (value.indexOf(prohibited[i]) > -1) {
return false;
}
}
return true;
}
arr = arr.filter(checker);
console.log(arr);
Obtain arr by splitting your title on space, eg title.split(" ").
Once you do any filtering you can create a filtered title with title = arr.join(" ").

How to translate an input using a function in JavaScript

So the goal of this task is translate english input values into french and vice versa. The problem here is that I don't know how to split the whole input by spaces to get all the words one by one and translate them one by one. Thank you :)
function translateInput(){
for(i = 0; i < ('input').length; i++){
('input').eq(i).val(('value').eq(i).text());
}
}
var translateText = function() {
var translationType = document.getElementById('translation').value;
if (translationType === 'englishToFrench') {
console.log('translation used: English to French');
return 'code1';
}else if(translationType === 'frenchToEnglish'){
console.log('translation used: French to English');
return 'code2';
}else{
return "No valid translation selected.";
}
};
You can use the split function to split the string at its spaces into an array.
var str = YOUR_STRING;
var array = str.split(" ");
http://www.w3schools.com/jsref/jsref_split.asp
Then you can loop through the array and translate word by word.
var arrayLength = array.length;
for (var i = 0; i < arrayLength; i++) {
alert(array[i]);
//Translate string
}
Or you can use a Regular Expression, by the way you can practice in a Regex Playground.
var myString = "Hello, my name is JavaScript";
var tokens = a.match(/\w+'?\w*/g); //Assuming you can take words like {"Bonsanto's", "Asus'"}
tokens.forEach(function(word){
console.log(word);
});

Javascript: matching a dynamic string against an array

I'm attempting to teach myself javascript. I chose something I assumed was simple, but ran into problems relatively quickly.
I'm attempting to search a string for another string given by the user.
My code so far is:
var source = "XREs2qqAQfjr6NZs6H5wkZdOES5mikexRkOPsj6grQiYNZfFoqXI4Nnc1iONKVrA";
var searchString = []; //the users input
searchString = prompt("Enter search string");
var hits = [];
var one = 0;
var two = 0;
var k = 0;
var sourceSearch = function(text) {
for(i = 0; i < source.length; i++) { //for each character in the source
if(source[i] === searchString[0]) { //if a character in source matches the first element in the users input
one = source.indexOf(i); //confused from here on
for(p = searchString.length; p > 0; p--) {
}
}
}
};
sourceSearch(searchString);
My idea was:
check to see if the first loop finds a character that matches the first character in the user input
if it matches, check to see if the next X characters after the first match the next X characters in the source string
if they all match, push them to the hits array
My problem: I have no idea how to iterate along the arrays without nesting quite a few if statements, and even then, that wouldn't be sufficient, considering I want the program to work with any input.
Any ideas would be helpful. Thanks very much in advance.
Note: There are a few un-used variables from ideas I was testing, but I couldn't make them work.
You can try:
if (source.indexOf(searchString) !== -1) {
// Match!
}
else
{
//No Match!
}
As the other answers so far point out, JavaScript strings have an indexOf function that does what you want. If you want to see how it's done "by hand", you can modify your function like this:
var sourceSearch = function(text) {
var i, j, ok; // always declare your local variables. globals are evil!
// for each start position
for(i = 0; i < source.length; i++) {
ok = true;
// check for a match
for (j = searchString.length - 1; ok && j >= 0; --j) {
ok = source[i + j] === searchString[j];
}
if (ok) {
// searchString found starting at index i in source
}
}
};
This function will find all positions in source at which searchString was found. (Of course, you could break out of the loop on the first success.) The logic is to use the outer loop to advance to each candidate start position in source and use the inner loop to test whether that position actually is the position of a match to searchString.
This is not the best algorithm for searching strings. The built-in algorithm is much faster (both because it is a better algorithm and because it is native code).
to follow your approach, you can just play with 2 indexes:
var sourceSearch = function(text) {
j = 0;
for(i = 0; i < source.length; i++) {
if(source[i] === text[j]) {
j++;
} else {
j = 0;
}
if (j == text.length) {
console.log(i - j); //this prints the starting index of the matching substring
}
}
};
These answers are all pretty good, but I'd probably opt for something like this:
var source = "XREs2qqAQfjr6NZs6H5wkZdOES5mikexRkOPsj6grQiYNZfFoqXI4Nnc1iONKVrA";
var searchString = []; //the users input
searchString = prompt("Enter search string");
var hits = source.split(searchString);
var hitsCount = hits.length - 1;
This way you have all of the data you need to figure out where each hit occurred in he source, if that's important to you.

Categories