How to check if part of a string is in an array? - javascript

user_input = "";
answer = "";
Array.greeting = ["hi", "hello"]
Array.names = ["john","james"]
user_input = document.getElementById('user_input').value.toLowerCase();
document.getElementById('text_input').innerHTML = user_input;
documnet.getElementById('say_something').innerHTML = say;
if(""){}
else{}
if(Array.greeting.includes(user_input) > 0){
say = "Hello";
}
if(Array.names.includes(user_input) > 0){
say = "User";
}
This is what i understand and have got up and running with correct outputs but how could i use input "hi john" and get output of "Hello User" with out baking it into an array?

You could do it like this:
var greetings = ["hi", "hello"];
var names = ["john","james"];
submit.onclick = function () {
// Split input into words, and convert that array to a Set for fast lookup
var words = new Set(user_input.value.split(/\s+/));
// Choose a greeting that is not among the input words.
// If all of them occur in the input, take the first greeting word
var greeting = greetings.find( greeting => !words.has(greeting)) || greetings[0];
// Choose a name that is not among the input words (or take the first)
var name = names.find( name => !words.has(name)) || names[0];
// Output with textContent (not innerHTML!)
text_input.textContent = user_input.value;
say_something.textContent = greeting + ' ' + name;
}
Input: <input id="user_input"><button id="submit">Submit</button><br>
You said: <span id="text_input"></span><br>
Reply: <span id="say_something"></span>
Obviously, when you enter both "hi" and "hello", the code will not find a greeting to use. In that case it uses the first greeting in the array ("hi"). The same principle applies for the names.

Let's simplify your requirement as:
You want to check if any element of an array "arr" contains part of string "s".
var check = function(arr, s) {
for (var i = 0; i < arr.length; i++) {
if (s.indexOf(arr[i]) > -1) {
return true;
}
}
return false;
}

Related

Changing the color of differences between two strings?

I want to compare two JS string variables. str1 and str2.
str1: is the reference text. it doesn't change.
str2: is the text which can be changed to be compared with str1.
So far I can track the differences between two strings but I want to change the color of the different parts to red on the sentence itself like this:
Here is the code that outputs this: moon in order you
// str2 is the text which I want to compare with str1.
var str2 = "I was sent to moon in order to protect you"
function words(s) {
return s.toLowerCase().match(/\w+/g);
}
// str1 is the reference text.
var str1 = "I was sent to earth to protect my cousin";
let a = words(str1);
let b = words(str2);
let res1 = b.filter(i => !a.includes(i));
let res2 = a.filter(i => !b.includes(i));
console.log(res1);
console.log(res2);
var str1 = res1.toString();
str1 = str1.replace(/,/g, '\n');
var str2 = res2.toString();
str2 = str2.replace(/,/g, '\n');
document.write(str1); // outputs: moon in order you
Using jQuery is preferred to change the text color.
Try like this. I have introduced a new function to highlight the word. if it matches I introduced a span tag and added a class.
// str2 is the text which I want to compare with str1.
var str2 = "I was sent to moon in order to protect you"
function words(s) {
return s.toLowerCase().match(/\w+/g);
}
// str1 is the reference text.
var str1 = "I was sent to earth to protect my cousin";
let a = words(str1);
let b = words(str2);
let res1 = b.filter(i => !a.includes(i));
let res2 = a.filter(i => !b.includes(i));
highlight(b, "str2", res1);
highlight(a, "str1", res2);
function highlight(str, id, res){
const div = document.createElement('div');
var text = "";
for(var i=0; i<str.length; i++){
var hasVal = res.includes(str[i]);
if(hasVal){
text +=" <span class='imp'>"+str[i]+"</span> ";
} else {
text +=" "+str[i]+" ";
}
}
div.innerHTML = text;
document.body.appendChild(div);
}
.imp{
color: red
}
You can look up the words in str2 which you've already established aren't present in str1. If you wrap these words in an HTML element you can give them any style you want. I've opted to mark the words with a black background to make them stand out more but you can apply whatever styling you want.
function words(s) {
return s.toLowerCase().match(/\w+/g);
}
function addToDOM(sentence) {
// Create a div, assign the str2 as its inner HTML and add it to
// the document.
const div = document.createElement('div');
div.innerHTML = sentence;
document.body.appendChild(div);
}
function highlightDifference(source, reference) {
let a = words(source);
let b = words(reference);
let res1 = b.filter(i => !a.includes(i));
let res2 = a.filter(i => !b.includes(i));
// Loop over the words in res2 not present in res1.
res2.forEach(word => {
// Replace the word with the word wrapped in an element.
source = source.replace(word, `<mark>${word}</mark>`);
});
addToDOM(source);
}
// This works as expected.
// str1 is the reference text.
var str1 = "I was sent to earth to protect my cousin";
// str2 is the text which I want to compare with str1.
var str2 = "I was sent to moon in order to protect you"
highlightDifference(str1, str2);
highlightDifference(str2, str1);
// This doesn't works as expected.
var world1 = 'Hi, I am Stan';
var world2 = 'Hi, Stan I am';
highlightDifference(world1, world2);
highlightDifference(world2, world1);
mark {
background-color: black;
color: white;
}
Unfortunately this strategy will get you in trouble for the following input:
str1 = 'Hi, I am Stan';
str2 = 'Hi, Stan I am';
It will not highlight any words changes as both sentences contain the exact same words but in a different order. You'll need a smarter strategy, something like this:
// str1 is the reference text.
var str1 = "Hi, I am Stan";
// str2 is the text which I want to compare with str1.
var str2 = "Hi, Stan I am"
function words(s) {
return s.match(/\w+/g);
}
function markWords(source, reference) {
var marked = [];
// Loop over all the words in source.
for (let index=0; index<source.length; index++) {
// Check if reference has fewer words or of the word at the
// same index is different from the word in source.
if (
reference.length < index ||
source[index] !== reference[index]
) {
// Words are not equal, mark the word.
marked.push(`<mark>${source[index]}</mark>`);
} else {
// Words are equal, output as is.
marked.push(source[index]);
}
}
// Return the array with (marked) words.
return marked;
}
function addToDOM(sentence) {
const div = document.createElement('div');
div.innerHTML = sentence;
document.body.appendChild(div);
}
let a = words(str1);
let b = words(str2);
// Mark the words in a which are different in b.
aMarked = markWords(a, b);
addToDOM(aMarked.join(' '));
// Mark the words in b which are different in a.
bMarked = markWords(b, a);
addToDOM(bMarked.join(' '));
mark {
background-color: black;
color: white;
}
This is the solution I came up with because I found other solutions that only worked when there was one difference, not multiple
function highlightDifferences(newValue, oldValue) {
if (oldValue === '' || newValue === oldValue) // Just return if the old value is empty or if the two values match
return newValue;
var highlightedCharacter = ""; // returnText will be modifed below
var oldValueArray = oldValue.split('');
var newValueArray = newValue.split('');
var returnArray = [];
for (var x = 0; x < newValue.split('').length; x++) {
if (oldValueArray[0] !== undefined && oldValueArray[0] === newValueArray[0]) {
returnArray.push(newValueArray[0]); // add the un-highlighted character to the return array
oldValueArray.shift(); // if the two characters are the same, drop them and move to the next character for comparison
newValueArray.shift();
}
else {
highlightedCharacter = '<span class="highlight">' + newValueArray[0] + '</span>';
returnArray.push(highlightedCharacter); // add the highlighted character to the return array
newValueArray.shift(); // remove the unmatched character from the array. oldValueArray is unchanged to compare to the next character in the newValue array
}
}
return returnArray.join('');
}
var oldValue = document.getElementById("oldValue").innerText;
var newValue = document.getElementById("newValue").innerText;
var text = highlightDifferences(newValue,oldValue);
document.getElementById("compared").innerHTML = text;
.highlight {
background-color: #fdff674d;
color: red;
}
<p>Old:</p>
<p id="oldValue">https://somedomain.info/ac834b89e</p>
<p>New:</p>
<p id="newValue">https://55some5domain.i555nfo/ac834b89e</p>
<p>Comparison:</p>
<p id="compared">to be replaced</p>

Highest occurrence in javascript

Hi my knowledge on javascript is very limited and basic. Basically below is I will prompt a pop-up that displays the answer to the value. The thing is from the coding I found below if I had to insert an array lets say 1,2,3,2 the output would be , since it has the highest occurrence in the array. Is there a way to edit this code so that the answer to the input above would be 2
I have done my fair share of research:
Here are the links:
Highest occurrence in an array or first selected
Get the element with the highest occurrence in an array
https://www.sitepoint.com/community/t/numbers-only-input-values-in-text-box-how/3029
Code:
<script type="text/javascript">
function evaluate() {
var input = prompt("Please enter your input");
var array = new Array();
function mode(array)
{
if(array.length == 0)
return null;
var modeMap = {};
var maxEl = array[0], maxCount = 1;
for(var i = 0; i < array.length; i++)
{
var el = array[i];
if(modeMap[el] == null)
modeMap[el] = 1;
else
modeMap[el]++;
if(modeMap[el] > maxCount)
{
maxEl = el;
maxCount = modeMap[el];
}
}
return maxEl;
}
document.writeln("Your calculation is: ");
document.writeln(mode(input) + " with a starting input string of: " + input);
}
</script>
<script type="text/javascript">
evaluate();
</script>
You want to convert the string '1,2,3,2' into the array [ 1, 2, 3, 2 ] first. this can be done with the split function. You probably also want to trim each element in case someone formats them with a space.
function evaluate() {
const input = prompt("Please enter the array of integers")
.split(',')
.map(item => item.trim());
function mode(items) {
const counts = items
.reduce((counts, item) => {
const currentItemCount = counts.get(item) || 0;
return counts.set(item, currentItemCount + 1);
}, new Map());
const maxEntry = Array.from(counts.entries())
.reduce((maxEntry, entry) => {
return entry[1] > maxEntry[1] ? entry : maxEntry;
});
return maxEntry[0];
}
document.writeln("Your calculation is: ");
document.writeln(mode(input) + " with a starting input string of: " + input);
}
evaluate();
Your issue stems from the fact that you never convert your input (which you receive from prompt as a string) into an actual array.
When mode is called directly on the string, the comma is returned as being the most common because comma is the most common character in the string.
To fix this, you need to convert your string into an actual array so you're operating on the elements of the array instead of the characters of the string.
You can use the split function to split your string ("1,2,3,2") at commas into an array (["1", "2", "3", "2"]) which you can then pass to the mode function:
mode(input.split(","))

How to reverse a string using loops in js

So I created this code and i was wondering how I would be able to loop depending on the amount of spaces there are in the userInput.
var userInput = prompt("Enter a phrase you want to reverse?")
var userOutput = ""
var array = []
var length = userInput.length;
var str = userInput.lastIndexOf(" ")
var test = userInput.substr(str, length);
The main Objective of this program is to reverse the userInput by not using js methods
Input:
"Hello world"
Output:
world Hello
1) Split the string on ' ', save to an array of strings
2) Reverse the array
3) Join the array elements with ' '
var userInput = prompt("Enter a phrase you want to reverse?")
var userOutput = ""
var array = []
var length = userInput.length;
var str = userInput.lastIndexOf(" ")
var test = userInput.substr(str, length);
var reversed = "";
while (length) {
reversed += test[--length];
}
Edit:
Woha! I should have been more careful using test.length instead of input length.
I will leave it for you as an practice to find and fix the bug I made.

Get Full string using part of a given string

var string = "Let's say the user inputs hello world inputs inputs inputs";
My input to get the whole word is "put".
My expected word is "inputs"
Can anyone share your solution?
Thanks in advance
One way to do what you're asking is to split the input string into tokens, then check each one to see if it contains the desired substring. To eliminate duplicates, store the words in an object and only put a word into the result list if you're seeing it for the first time.
function findUniqueWordsWithSubstring(text, sub) {
var words = text.split(' '),
resultHash = {},
result = [];
for (var i = 0; i < words.length; ++i) {
var word = words[i];
if (word.indexOf(sub) == -1) {
continue;
}
if (resultHash[word] === undefined) {
resultHash[word] = true;
result.push(word);
}
}
return result;
}
var input = 'put some putty on the computer output',
words = findUniqueWordsWithSubstring(input, 'put');
alert(words.join(', '));
A RegEx and filter to remove duplicates;
var string = "I put putty on the computer. putty, PUT do I"
var uniques = {};
var result = (string.match(/\b\w*put\w*\b/ig) || []).filter(function(item) {
item = item.toLowerCase();
return uniques[item] ? false : (uniques[item] = true);
});
document.write( result.join(", ") );
// put, putty, computer

jQuery removing values from a comma separate list

Given an input like:
<input type="test" value="3,4,9" />
What's the best way to remove a value like 9, 4 or 3, without having issues with the commas, I don't want this ending up:
value="3,4,"
value="3,,9"
value=",4,9"
Is there a clean way to get this done in JavaScript/jQuery?
You could split your value into an array, then filter out values you do not want.
$("input[type='test']").val().split(",") // ["3","4","9"]
.filter(function(v){return !isNaN(parseInt(v))}) // filter out anything which is not 0 or more
Here is a less terse version which filters out anything which is not numeric
var array = $("input[type='test']").val().split(",");
// If you are dealing with numeric values then you will want
// to cast the string as a number
var numbers = array.map(function(v){ return parseInt(v)});
// Remove anything which is not a number
var filtered = numbers.filter(function(v){ return !isNaN(v)});
// If you want to rejoin your values
var joined = filtered.join(",");
Finally change the value on the input
$("input[type='test']").val(joined);
Similar to PHP implode/explode functions
Array.prototype.remove = function(from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};
var explode = value.split(',');
explode.remove(1);
var implode = explode.join(',');
Documentation:
fce: Split
fce: Join
fce: Array.remove
No jQuery required :P
<script type="text/javascript">
//var subject = '3,4,9';
//var subject = '3,,9';
var subject = ',,4,9';
var clean = Array();
var i = 0;
subject = subject.split(',');
for (var a in subject)
{
if(subject[a].length)
{
clean[i] = subject[a];
i++;
}
}
document.write(clean.join(','));
</script>
You may also use pure javascript. Let say you want to take off only "4":
value = value.replace(/4,?/, '')
or "3" and "9":
value = value.replace(/([39],?)+/, '')
I think this function will work for what you are trying to do: http://www.w3schools.com/jsref/jsref_split.asp
string.split(separator, limit)
use
array = string.split(separator);
to break a string into an array. then use this to join after manipulations.
string = array.join(separator);
var ary = value.split(',');
ary.splice(indexOfItemToRemove,1)
var result = ary.join(',');
This is discussed in another post:
remove value from comma separated values string
var removeValue = function(list, value, separator) {
separator = separator || ",";
var values = list.split(",");
for(var i = 0 ; i < values.length ; i++) {
if(values[i] == value) {
values.splice(i, 1);
return values.join(",");
}
}
return list;
}
You can use this function:
function removeComma(x) {
var str = '';
var subs = '';
for(i=1; i<=x.length; i++) {
subs = x.substring(i-1, i).trim();
if(subs !== ',') {
str = str+subs;
}
}
return str;
}

Categories

Resources