Comparing array elements to character - javascript

I'm trying to write a simple javascript program to check if a letter is a vowel. The problem is the output is incorrect and should say that " a is a vowel."
Javascript:
function findvowel(letter1, vowels) {
var count = vowels.length;
for (var i = 0; i < count; i++) {
if (vowels[i] === letter1) {
var message1 = " is a vowel";
document.getElementById('exercise3').innerHTML = letter1 + message1;
} else {
var message2 = " is a consonant";
document.getElementById('exercise3').innerHTML = letter1 + message2;
}
}
}
HTML:
<script>
$(document).ready(function() {
findvowel("a",["a","e","i","o","u"]);
});
</script>
Output:
a is a consonant

Add break to your loop so it doesn't keep going.
function findvowel(letter1, vowels) {
var count = vowels.length;
for (var i = 0; i < count; i++) {
if (vowels[i] === letter1) {
var message1 = " is a vowel";
document.getElementById('exercise3').innerHTML = letter1 + message1;
break;
} else {
var message2 = " is a consonant";
document.getElementById('exercise3').innerHTML = letter1 + message2;
}
}
}
You can actually use return false; to stop your function right away when a vowel is matched, however in normal cases break will be used because there might be other codes going on after the loop.
BTW:
function findvowel(letter){
//thanks p.s.w.g for reminding me []
return letter+" is a "+(/[aeiou]/i.test(letter)?"vowel":"constant");
}

You're testing the vowel in the for-loop and updating the output every time. So the output will only display if the last vowel that was tested matched the input. Instead, you should break out of the for-loop if a vowel is found, and only display a failure (" is a consonant") after you've tested all the vowels and you weren't able to find a match:
var count = vowels.length;
for (var i = 0; i < count; i++) {
if (vowels[i] === letter1) {
var message1 = " is a vowel";
document.getElementById('exercise3').innerHTML = letter1 + message1;
return;
}
}
var message2 = " is a consonant";
document.getElementById('exercise3').innerHTML = letter1 + message2;
But this method could be simplified to:
function findvowel(letter1) {
var isVowel = "aeiou".indexOf(letter1) > -1;
var message = letter1 + " is a " + (isVowel ? "vowel" : "consonant");
document.getElementById('exercise3').innerHTML = message;
}

This is what I would do, using native functions:
var letter = "a";
var isVowel = ["a","e","i","o","u"].some(function(vowel){
return vowel === letter;
});
Rergarding your message, I would try something like:
var message = letter + (isVowel ? " is a vowel" : " is a consonant");

I would pass in an object instead of an array and take advantage of the constant time lookup using the 'in' keyword. No need for a loop.
function findvowel(letter1, vowels) {
if (letter1 in vowels) {
var message1 = " is a vowel";
document.getElementById('exercise3').innerHTML = letter1 + message1;
} else {
var message2 = " is a consonant";
document.getElementById('exercise3').innerHTML = letter1 + message2;
}
}
then
var obj = {'a': true, 'e': true, 'i': true, 'o': true, 'u': true}
then call it
findvowel('a', obj)

Since you're already using jQuery, which offers $.inArray(), why don't you do this?
var vowels = ["a", "e", "i", "o", "u"];
$(document).ready(function() {
var letter = 'u';
var found = $.inArray(letter, vowels) > -1;
if(found) {
console.log(letter + ' is a vowel');
} else {
console.log(letter + ' is a consonant');
}
});

Related

Trying to push a letter into an array to display on page

var secretWord = [];
var underScoreWord = [];
var wins = 0;
var guessesRemaining = 10;
var alreadyGuessed = [];
var wordLetter = true;
//Assign HTML elements to variables
var cityText = document.getElementById("city-text");
var winsNum = document.getElementById("wins-num");
var guessesNum = document.getElementById("guesses-num")
var lettersGuessed = document.getElementById("letters-guessed")
//Array of cities
var city = ["Paris", "Wellington", "Hanoi", "Perth", "Marseille", "London", "Ottawa", "Zurich", "Boston", "Tokyo", "Detroit"];
//console.log(city);
//Pick random word from the team array and push the result to an empty array.
function pickRandomCity() {
var randomCity = city[Math.floor(Math.random() * city.length)];
secretWord = randomCity.split('');
return randomCity;
}
var cityPicked = pickRandomCity();
//Get length of secretWord and push as underscores to am empty array
for (var i = 0; i < cityPicked.length; i++) {
underScoreWord.push("_");
}
console.log('secretWord : ' + secretWord);
// console.log('underScoreWord : ' + underScoreWord);
// console.log('------------------');
// console.log('cityPicked : ' + cityPicked);
//Check for letters
//Listen for key press and check to see if its a match
document.onkeyup = function letterCheck(event) {
var userGuess = event.key;
for (var j = 0; j < secretWord.length; j++) {
if (userGuess.toUpperCase() === secretWord[j].toUpperCase()) {
wordLetter = true;
underScoreWord[j] = userGuess;
guessesRemaining--;
}
else if (!wordLetter) {
alreadyGuessed.push();
// guessesRemaining--;
}
}
console.log("Already guessed: " + alreadyGuessed);
lettersGuessed.textContent = ("Letters already guessed: " + alreadyGuessed);
// Write to page
cityText.textContent = underScoreWord.join(" ");
winsNum.textContent = ("Wins: " + wins);
guessesNum.textContent = ("Guesses Remaining: " + guessesRemaining);
console.log(underScoreWord);
}
Does anybody know how can I push userGuess to an empty array and then display? As you can see I managed to push the userGuess to the alreadyGuessed array but it only displays one character at a time on the page.
The end goal is for the alreadyGuessed array to display like this - Letters alreadyGuessed: a g r h e t
You can store what keys have been pressed with an object, and at the beginning of each keyup event, check if user has pressed it.
I also switched the for loop to map
var guessedLetters = {};
document.onkeyup = function letterCheck(event) {
var userGuess = event.key;
if (!guessedLetters[userGuess.toUpperCase()]) { // check if user pressed this key
alreadyGuessed.push(userGuess.toUpperCase());
guessedLetters[userGuess.toUpperCase()] = true;
guessesRemaining--;
} else { // this key has been pressed before, dont do anything
return;
}
secretWord.map((n, i) => {
if (userGuess.toUpperCase() === n.toUpperCase()) {
underScoreWord[i] = n;
}
})
console.log("Already guessed: " + alreadyGuessed);
lettersGuessed.textContent = ("Letters already guessed: " + alreadyGuessed);
// Write to page
cityText.textContent = underScoreWord.join(" ");
winsNum.textContent = ("Wins: " + wins);
guessesNum.textContent = ("Guesses Remaining: " + guessesRemaining);
console.log(underScoreWord);
}
Looks like wordLetter is a global variable initialized to true. Also looks like it is never set to false so your call to alreadyGuessed.push(userGuess); will never be reached since !wordLetter is always false.
Try alreadyGuessed.push(userGuess); inside your event listener's elseif statement.
EDIT:
As per the suggestion from #foxinatardis, the way you modify and check for wordLetter inside your loop needs to be changed:
if (userGuess.toUpperCase() === secretWord[j].toUpperCase()) {
wordLetter = true;
underScoreWord[j] = userGuess;
guessesRemaining--;
} else {
wordLetter = false;
alreadyGuessed.push(userGuess);
// guessesRemaining--;
}
You actually don't need the wordLetter variable anymore with this change, unless you're using it elsewhere for something else.

Split String into dictionary words and non-dictionary words

I want to split a string into a sequence of words using a dictionary.
The following function only gives me words with letter boundaries.
function spltToWord(prm){
var spltedAr = prm.split(/(?=[A-Z][a-z])/);
return spltedAr.join(" ").trim();
}
I want to separate the text into dictionary/non-dictionary words.
For example:
Iamno123prisoner - I am no 123 prisoner
USAisveryrich - USA is very rich
Albertgaveme5rupees - Albert gave me 5 rupees
A sample dictionary can be found Here for refrence.
If the dictionary contains many words, you'll want a faster solution than matching one word at a time against substrings of the input text. If there are ten thousand words in the dictionary, you have to do at least ten thousand character comparisons with this naive approach.
A more efficient solution involves the use of a trie in which you've stored the dictionary words. Checking whether a word is in the dictionary requires only a single pass through the string.
Another advantage is that you can search for the longest match starting from a given position in the text. This approach is demonstrated in the following snippet, which includes a small dictionary that suffices to process your examples. You can replace this with your own dictionary when you run the code locally.
var Global = {
dictionary: [
'aa', 'I', 'i', 's',
'aah', 'am',
'aahed', 'no',
'aahing', '123',
'aahs', 'prisoner',
'aal', 'USA',
'aalii', 'is',
'aaliis', 'very',
'aals', 'rich',
'aardvark', 'Albert',
'aardvarks', 'gave', 'me', '5', 'rupees'
]
};
function addToTrie(word) {
var node = Global.trie;
for (var pos = 0; pos < word.length; ++pos) {
var letter = word.charAt(pos);
if (node[letter] === undefined) {
node[letter] = {};
}
node = node[letter];
}
node.terminal = true;
}
function findLongestMatch(text, start) {
var node = Global.trie,
best = start - 1;
for (var pos = start; pos < text.length; ++pos) {
var letter = text.charAt(pos);
if (node[letter] === undefined) {
break;
}
node = node[letter];
if (node.terminal) {
best = pos;
}
}
return best - start + 1;
}
function loadTrie() {
var words = Global.dictionary,
trie = Global.trie = {};
words.forEach(function (word) {
addToTrie(word);
});
};
function println(label, s, labelStyle) {
if (s === undefined) {
s = label || '';
} else {
var className = 'label' + (labelStyle ? ' ' + labelStyle : '');
s = '<div class="' + className + '">' + label + '</div> ' + s;
}
document.getElementById('message').innerHTML += (s + '<br />');
}
function process(text) {
var results = [],
letters = [],
pos = 0;
while (pos < text.length) {
var length = findLongestMatch(text, pos);
if (length == 0) {
letters.push(text.charAt(pos));
pos += 1;
} else {
if (letters.length != 0) {
results.push({ word: letters.join(''), known: false });
letters = [];
}
results.push({ word: text.substring(pos, pos + length), known: true });
pos += length;
}
}
if (letters.length != 0) {
results.push({ word: letters.join(''), known: false });
letters = [];
}
var breakdown = results.map(function (result) {
return result.word;
});
println();
println(' breakdown:', '/' + breakdown.join('/') + '/');
results.forEach(function (result) {
println((result.known ? 'in dictionary' : ' unknown') + ':',
'"' + result.word + '"', (result.known ? undefined : 'unknown'));
});
};
window.onload = function () {
loadTrie();
process('WellIamno123prisoner');
process('TheUSAisveryrichman');
process('Albertgaveme5rupeesyo');
};
body {
font-family: monospace;
color: #444;
font-size: 14px;
line-height: 20px;
}
.label {
display: inline-block;
width: 200px;
font-size: 13px;
color: #aaa;
text-align: right;
}
.label.unknown {
color: #c61c39;
}
<div id="message"></div>
Edit #2
var words = ["apple", "banana", "candy", "cookie", "doughnut"];
var input = "banana123candynotawordcookieblahdoughnut";
var currentWord = "",
result = "";
while (true) {
for (var i = 0; i < input.length; i++) {
currentWord += input[i];
if (words.indexOf(currentWord) >= 0) {
result += " " + currentWord + " ";
currentWord = "";
}
}
if (currentWord.length > 0) {
result += currentWord[0];
input = currentWord.substr(1);
currentWord = "";
} else {
break;
}
}
console.log(result.trim()); // "banana 123 candy notaword cookie blah doughnut"
Note the result will contain two spaces if there are two consecutive dictionary words. You can fix this using regex.
It isn't the prettiest solution (you can make it recursive which may be more readable), and it doesn't provide multiple solutions (see DP link in comment for that).
Edit this doesn't take into account non-dictionary words.
Using a simple greedy algorithm:
var words = ["apple", "banana", "candy", "cookie", "doughnut"];
var input = "bananacandycookiedoughnut";
var currentWord = "", result = "";
for (var i = 0; i < input.length; i++) {
currentWord += input[i];
if (words.indexOf(currentWord) >= 0) {
result += currentWord + " ";
currentWord = "";
}
}
console.log(result.trim()); // "banana candy cookie donught"
Of course you would want to modify various part of this, e.g. use a set for the dictionary and take into account case [in]sensitivity.

display the recursion line by line

I am trying to make a function in javascript that would expand/split a string with dashes and show the process ( line by line ) using recursion.
for example, the string "anna" would become:
expand("anna") = expand("an")+"---"+expand("na") ->
"a"+"---"+"n"+"---"+"n"+"---"+"a"
and the desired output would be:
anna
an---na
a---n---n---a
I have achieved doing the following so far (I know it might not be the solution I am looking):
expand("anna") = an+"---"+expand("na")
= an+"---"+n+"---"+expand("a");
= an+"---"+n+"---+"a"
the output I am getting is:
an---n---a
I can't seem to concatenate the head though to do the first example.
My javascript function of expand is as follows:
function expand(word) {
if (word.length<=1) {
return word;
} else {
mid = word.length/2;
return word.substr(0,mid) + " " + expand(word.substr(mid,word.length));
}
}
document.write(expand("anna"));
I would need some tips to do this, otherwise (if it's the wrong stackexchange forum), please guide me where to post it.
this is my crazy attempt
var Word = function(str) {
this.isSplitable = function() {
return str.length > 1;
}
this.split = function() {
var p = Math.floor(str.length / 2);
return [
new Word(str.substr(0,p)),
new Word(str.substr(p,p+1))
];
}
this.toString = function() {
return str;
}
}
var expand = function(words) {
var nwords = [];
var do_recur = false;
words.forEach(function(word){
if(word.isSplitable()) {
var splitted = word.split();
nwords.push(splitted[0]);
nwords.push(splitted[1]);
do_recur = true;
}else{
nwords.push(word);
}
});
var result = [];
nwords.forEach(function(word){
result.push( word.toString() );
});
var result = result.join("--") + "<br/>";
if(do_recur) {
return result + expand(nwords);
}else{
return "";
}
}
document.write( expand([new Word("anna")]) );
This is what you need
expand = function(word) {
return [].map.call(word, function(x) {return x+'---'}).join('')
};
The joy of functional programming.
And with added code to deal with last character:
function expand(word) {
return [].map.call(word, function(x, idx) {
if (idx < word.length - 1)
return x+'---';
else return x
}).join('')
}
As I said that it is impossible to display the "process" steps of recursion while using recursion, here is a workaround that will output your desired steps:
var levels = [];
function expand(word, level) {
if (typeof level === 'undefined') {
level = 0;
}
if (!levels[level]) {
levels[level] = [];
}
levels[level].push(word);
if (word.length <= 1) {
return word;
} else {
var mid = Math.ceil(word.length/2);
return expand(word.substr(0, mid), level+1) + '---' + expand(word.substr(mid), level+1);
}
}
expand('anna');
for (var i = 0; i < levels.length; i++) {
console.log(levels[i].join('---'));
}
to see all steps the best that I whold do is:
function expand(word) {
if (word.length<=1) {
return word;
} else {
var mid = word.length/2;
var str1 = word.substr(0,mid);
var str2 = word.substr(mid,word.length);
document.write(str1 + "---" + str2 + "<br></br>");
return expand(str1) + "---" + expand(str2);
}
}
document.write(expand("anna"));
You have to return the two parts of the string:
function expand(word) {
output="";
if (word.length<=1) {
output+=word;
return output;
} else
{
var mid = word.length/2;
output+=word.substr(0,mid)+"---"+word.substr(mid)+" \n";//this line will show the steps.
output+=expand(word.substr(0,mid))+"---"+expand(word.substr(mid,word.length-1))+" \n";
return output;
}
}
console.log(expand("anna"));
Edit:
I added the output var and in every loop I concatenate the new output to it.
It should do the trick.
Hope the problem is in your first part. According to your algorithm, you are splitting your string anna in to two parts,
an & na
so you need to expand both parts until the part length is less than or equal to one. so your required function is the below one.
function expand(word) {
if (word.length<=1) {
return word;
} else {
mid = word.length/2;
return expand(word.substr(0,mid)) + " --- " + expand(word.substr(mid,word.length));
}
}
document.write(expand("anna"));

How to join a string in javascript based on a regex or if string starts with some value?

for instance I have this string:
013227004871996 300234060903250 013227003498171 013227003493834 300234010640390
013227003512963 300234061401690 013227004865956 013226009142122 013227008391574
300234061405690 013227003400573 300234061404700 013227003501479 013227003394495
013227004876284 300234061349230 013227004876284 013227004862011
and what I want to happen is that to separate the entry if it encounters 01322, so for instance in the example it will have array[0] = 013227004871996 300234060903250, array[1] = 013227003498171,
array[2] = 013227003493834
so basically I want to split it if the next entry starts with "013227".
This seems to work. Im matching everything that starts and is followed by 013227. Then I'm matching the last segment with .+
str.match(/013227.+?(?=013227)|.+/g)
Or even better:
str.split(/(?=013227)/)
var numbersStr = "013227004871996 300234060903250 013227003498171 013227003493834 300234010640390 013227003512963 300234061401690 013227004865956 013226009142122 013227008391574 300234061405690 013227003400573 300234061404700 013227003501479 013227003394495 013227004876284 300234061349230 013227004876284 013227004862011";
var pattern = new RegExp('01322[\\d]+');
var numbersArr = numbersStr.split(' ');
var numbersArrLength = numbersArr.length - 1;
for (var i = numbersArrLength; i >= 0; i--) {
if (!pattern.test(numbersArr[i])) {
numbersArr.splice(i, 1);
}
}
var separator = '01322';
"013227004871996 300234060903250 013227003498171 013227003493834 300234010640390"
.split(separator)
.filter(function(item){
return item;
}).map(function(item){
return separator + item;
})
var s = "013227004871996 300234060903250 013227003498171 013227003493834 300234010640390 "
+ "013227003512963 300234061401690 013227004865956 013226009142122 013227008391574 "
+ "300234061405690 013227003400573 300234061404700 013227003501479 013227003394495 "
+ "013227004876284 300234061349230 013227004876284 013227004862011";
var sp = s.split(" ");
var res = new Array();
var count=0;
sp.forEach(function(a) {
if(a.search("01322") === 0) {
if(res[count] === undefined) {
res[count] = a;
} else {
++count;
res[count] = a;
}
} else {
if(res[count] === undefined) {
res[count] = a;
} else {
res[count]+=" "+a;
}
}
});
console.log(res);
[ '013227004871996 300234060903250',
'013227003498171',
'013227003493834 300234010640390',
'013227003512963 300234061401690',
'013227004865956',
'013226009142122',
'013227008391574 300234061405690',
'013227003400573 300234061404700',
'013227003501479',
'013227003394495',
'013227004876284 300234061349230',
'013227004876284',
'013227004862011' ]
try this
function niceslice( string, delimiter ){
var result = string.split(delimiter);
for(var i = 1; i < result.length; i++){
result[i] = delimiter + result[i];
}
return result;
}
take note that this will not eliminate spaces in your example (but should be easily built in)
example usage
var str = 'anton albert andrew';
var output = niceslice( str, 'a' );
console.log( output ); // returns ['', 'anton ', 'albert ', 'andrew']
or in your case
var str = '013227004871996 300234060903250 013227003498171 013227003493834 300234010640390 013227003512963 300234061401690 013227004865956 013226009142122 013227008391574 300234061405690 013227003400573 300234061404700 013227003501479 013227003394495 013227004876284 300234061349230 013227004876284 013227004862011';
var output = niceslice( str, '013227' );

How to replace all capture groups if it is generated dynamically?

Consider the following code:
function Matcher(source, search) {
var opts = search.split('');
for (var i = 0; i < opts.length; i++) {
opts[i] = '(' + opts[i] + ')';
}
opts = opts.join('.*');
var regexp = new RegExp(opts, 'gi');
source = source.replace(regexp, function () {
console.log(arguments);
return arguments[1];
});
return source;
}
You call the function passing the source as the first parameter and what you need to match as the second one.
What i need is to replace all capture groups with a bold tag around the coincidence.
As an example, consider the following:
var patt = /m([a-z0-9\-_]*?)r([a-z0-9\-_]*?)i([a-z0-9\-_]*?)e([a-z0-9\-_]*\.[a-z]+)/gi;
var newFileName = fileName.replace(patt, "<strong>m</strong>$1<strong>r</strong>$2<strong>i</strong>$3<strong>e</strong>$4");
This code is an answer from Terry on my previous question but the problem here is that you need to know exactly what you want to replace, and i need it dynamically.
Any thoughts?
It seems like you're creating the pattern the wrong way round. Instead of building a(.*?)b(.*?)c, you create (a).*(b).*(c) - with the capturing groups around the parts you already know. Better:
function wrapEachLetter(source, search, tag) {
var opts = search.split('');
tag = tag || "strong";
return source.replace(new RegExp(opts.join("(.*?)"), 'gi'), function () {
var str = '<'+tag+'>'+opts[0]+'</'+tag+'>';
for (var i=1; i<opts.length; i++)
str += arguments[i] + '<'+tag+'>'+opts[i]+'</'+tag+'>';
return str;
});
}
Example:
> wrapEachLetter("testExampleString", "tex", "b")
"<b>t<b><b>e<b>stE<b>x<b>ampleString"
Capture the delimiters too and then process only even subgroups, leaving odd ones as is:
s = "ABC---DEF---HIJ"
re = /(\w+)(.*?)(\w+)(.*?)(\w+)/
s.replace(re, function() {
return [].slice.call(arguments, 1, -2).map(function(a, n) {
return n & 1 ? a : "<strong>" + a + "</strong>"
}).join("")
})
> "<strong>ABC</strong>---<strong>DEF</strong>---<strong>HIJ</strong>"
However, if your goal is to highlight only individual characters, it's much simpler this way:
str = "myfile.js"
letters = "mis"
re = new RegExp("[" + letters + "]", "gi")
str.replace(re, "<b>$&</b>")
> "<b>m</b>yf<b>i</b>le.j<b>s</b>"
or, without regular expressions:
str = "myfile.js"
letters = "mis"
str.split("").map(function(s) {
return letters.indexOf(s) >= 0 ? "<b>" + s + "</b>" : s
}).join("")
> "<b>m</b>yf<b>i</b>le.j<b>s</b>"
var input = "aBcDeFgHiJk",
match = 'be';
str = '',
reg = '',
i = 0;
function escapeRegExp(c) {
return c.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
// /(.*)(b)(.*)(e)(.*)/gi
// '$1<b>$2</b>$3<b>$4</b>$5'
for (var c in match) {
if (i == 0) {
str += '$' + ++i;
reg += '(.*)';
i++;
}
str += '<b>$' + i++ + '</b>$' + i++;
reg += '(' + escapeRegExp(match[c]) + ')(.*)';
}
alert(input.replace(new RegExp(reg, 'ig'), str)); // <- a<b>B</b>cD<b>e</b>FgHiJk

Categories

Resources