Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
My goal is to create a "typoglycemia generator" using HTML CSS JS.
I.e. A web App which takes the user input and mixes up the letters of each word except for the first and last letter.
For example: USER INPUT = "Hello everyone at stackoverflow"; OUTPUT = "Hlelo eevrnyoe at satckoeovrflw"!
I am new to JS, can anyone guide me as to what the steps would be to create this JS code.
Thanks in advance!
Detailed explanation after snippet.
function shuffle(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
function Typoglycemia(word) {
var letters=word.split("");
var first=letters.shift();
var last=letters.pop();
var shuffled=shuffle(letters);
shuffled.push(last);
shuffled.unshift(first);
var typoglycemia=shuffled.join("");
return typoglycemia;
}
function TypoglycemiaWord(word) {
document.getElementById("sTypoglycemiaWord").innerText = Typoglycemia(word);
}
function TypoglycemiaSentence(sentence) {
var words=sentence.split(" ");
var typoglycemias=words.map(word=>Typoglycemia(word));
document.getElementById("sTypoglycemiaSentence").innerText = typoglycemias.join(" ");
}
Enter a word: <input onchange="TypoglycemiaWord(this.value)"><br>
Typoglycemia: <span id="sTypoglycemiaWord">result here</span><br>
<br>
Enter a sentence: <input onchange="TypoglycemiaSentence(this.value)"><br>
Typoglycemia: <span id="sTypoglycemiaSentence">result here</span>
First thing we do is remove and save first and last letters.
It's done in function Typoglycemia that takes a word as it's parameter.
We split that word into letters by telling split to split every time it sees "" = nothing = just split.
shift removes the first element of an Array - we store that in first.
pop removes the last element of an Array - we store that in last.
We need a shuffling function - function shuffle - that takes an Array - array as it's parameter.
It goes from last element back to the second - Arrays are zero-indexed, so back to index 1, which is one after index 0 = the first element.
It randomly swaps, goes back, until done, and returns a shuffled array.
Back to Typoglycemia function:
We add last back to the end using push, and first back to the beginning using unshift.
Lastly, we join the array with no spaces "" and return it.
The rest, for word, is simpler HTML and JavaScript.
For sentences, we split by spaced " ", map each word to it's Typoglycemiad value, and then join the result with a space " " between each word.
The rest, for sentence, is simpler HTML and JavaScript.
The rest: Hitting ENTER in an input element calls a function, passing to it the value of itself (this).
TypoglycemiaWord and TypoglycemiaSentence do what they do (as explained above), and send the result to a span element that is found by using it's id in document.getElementById, by setting it's innerText to that result.
Hope this was fun as it was educational!
Related
This question already has answers here:
Length of a JavaScript object
(43 answers)
Closed 2 years ago.
Lately I have been trying to create a webpage with a search feature. My way of implementing this, while not the fastest or most elegant, should work in theory. All it does is split the search term into a list, the delimiter being a space, and then splits the keywords (in dictionary format, with the value being a download link, and with the key being the "keywords" I was referring to) and finally, it has an outer loop looping through the keys (being split each iteration into a list), and an inner loop looping through the words input through the input field. If a word in the search field matches one keyword of the key words list, then that key from the dictionary gets a score of +1.
This should sort the keys into order of best result to worst, and then the code can continue on to process all this information and display links to the downloadable files (the point of the webpage is to supply downloads to old software [of which I have collected over the years] etc.). However, when I run the program, whenever the alert(ranking.length) function is called, all I get is undefined in the output window.
Here is the code. (The search() function is called whenever the search button is pressed):
var kw_href = {
"windows":["windows3.1.7z"],
"ms dos 6.22":["ms-dos 6.22.7z"]
}
function search(){
var element = document.getElementById("search_area");
var search_term = element.value.toLowerCase();
var s_tags = search_term.split(" ");
var keys = Object.keys(kw_href);
ranking = {
"windows":0,
"ms dos 6.22":0
};
for (i = 0; i < keys.length; i++){
keywords_arr = keys[i].split(" ");
for (x = 0; x < s_tags.length; x++){
if (keywords_arr.includes(s_tags[x])){
ranking[keys[i]] = ranking[keys[i]] + 1;
}
}
}
// now we have a results list with the best results. Lets sort them into order.
alert(ranking.length);
}
Edit
alert(ranking.length) line is for debugging purposes only, and I was not specifically trying to find the length.
ranking is a generic object, not an array, so it won't have a computed length property.
If you want to count the number of properties in it, convert it to an array with Object.keys(ranking).
ranking should be array of object like ranking =[{"windows":0,"ms dos 6.22":0},{"windows":1,"ms dos 6.22":10}]
Then length ranking.length will work
This question already has answers here:
Loop (for each) over an array in JavaScript
(40 answers)
Closed 4 years ago.
Let me preface my question by saying that I'm a beginning software engineering student in an Intro to JavaScript course. I'm having an issue with an assignment for the JavaScript course.
Here is the assignment, "Create a file called nameSplit.html that uses one single prompt() call to get a full name from the user--first, middle and last name. Then, split the input into an array and use a loop to output each name on a separate line. For full credit, you must use a loop rather than joining the array back into a string."
My issue is that when I write the split string to the page, it writes the split string multiple times on separate lines which isn't what I want. What I want is for the string to separate and each part to be on a separate line.
Here's my code.
var fullName = prompt("Please enter your full name: first, middle (if you have one), and last name.", "Full Middle Last");
function nameSplit(name) {
var nameAfterSplit = name.split(" ");
for (i = 0; i < nameAfterSplit.length; i++) {
document.write(nameAfterSplit + "<br />");
}
}
nameSplit(fullName);
Can anyone help me with this?
String.split generates an array and you're printing the whole array inside the loop. You must use the index [i] to select a specific array element.
Change to:
document.write(nameAfterSplit[i] + "<br />");
You should output the i-th element of the array containing the split parts: use nameAfterSplit[i] instead of nameAfterSplit
Look closely at what you're printing. While you do split() your string correctly, when you print it you're printing not just each segment but the whole split-string. As split returns an array, what you need to do is target each individual element on each loop iteration.
var fullName = prompt("Please enter your full name: first, middle (if you have one), and last name.", "Full Middle Last");
function nameSplit(name){
var nameAfterSplit = name.split(" ");
for(i = 0; i < nameAfterSplit.length; i++){
document.write(nameAfterSplit[i] + "<br />");
}
}
nameSplit(fullName);
I am currently studying another user’s code for a coding question from LeetCode. My question is about certain aspects of his code. Here’s a link to the question.
Question:
Why does this user use a # to mark the end of the array?
Under the second if case, the user writes:
ans.push(nums[t] + '->' + (nums[i-1]))
Now, I understand what this statement does. My question is: Why does this produce an output of ["0->2",...] instead of [0"->"2,...]?
var summaryRanges = function(nums) {
var t = 0
var ans = []
nums.push('#')
for(var i=1;i<nums.length;i++)
if(nums[i]-nums[t] !== i-t){
if(i-t>1)
ans.push(nums[t]+'->'+(nums[i-1]))
else
ans.push(nums[t].toString())
t = i
}
return ans
}
The algorithm depends on that the difference between nums[i] and nums[t] is not the same as the difference between i and t. When that happens, the algorithm adds more to the output. This creates a special case when the last range is just a single number, since this cannot trigger the condition.
Hence the hash character is padding to extend the array in order to make the algorithm work, so that the condition nums[i]-nums[t] !== i-t will trigger even for a finishing range of a single number. It could be any string really as long as it is not an integer number.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Hi I am developing a small application in JSP.
My idea is to give reference to a JSON element while user is typing in the text area.
for example:
If my JSON contains:
cO2,
H2O,
c9O
and in the text area the user is typing a sentence and as soon as the user types a special character such as # or \ or / if he/she writes "c" character I want a small drop down to appear with the two elements starting with c.
The user can select the element afterwards and then when the form is posted I want to extract those information which was entered from JSON.
This is like when you start typing a name in Facebook I guess.
Any ideas?
Thanks in advance
EDIT: JS Fiddle
<form action="./Protocol" method="POST">
<textarea rows=5 cols=50></textarea>
<input type="submit"/></form>
$('textarea').textcomplete([{
match: /(^|\s)(\w{2,})$/,
search: function (term, callback) {
var words = ['google', 'facebook', 'github', 'microsoft', 'yahoo'];
callback($.map(words, function (word) {
return word.indexOf(term) === 0 ? word : null;
}));
},
replace: function (word) {
return word + ' ';
}}]);
The above JS Fiddle does what I want partly.
One of the two things I want to accomplish here
1. if in the JSON, each word has an ID like {"ID": "1","name": "GOOGLE"} can I get the IDs that are in the textarea to be posted when the form is posted
2. or just the array index numbers, how do I POST the values in the form separately from the textarea.
OK, despite what I said, here's a basic example of how you might achieve this (because I was bored, but not so bored I'm going to do it all for you :)):
HTML
<input id="input"/>
<div id="dropdown"></div>
JS
// grab the DOM elements
var input = document.getElementById('input');
var dropdown = document.getElementById('dropdown');
// assign an function to the onkeyup event for your input box
input.onkeyup = search;
// define your data structure
var arr = ['cO2', 'H2O', 'c9O'];
function search() {
// get the content and length of the content
// `this` in this instance refers to the element to which
// we assigned the function
var val = this.value;
var len = val.length;
// filter out the elements from the array that match
// the content, or nothing if the input is empty
dropdown.textContent = arr.filter(function(el) {
return val !=='' ? el.substring(0, len) === val : '';
});
}
DEMO
Hope that helps you on your way.
I am sorry for the very newbie question, but this is driving me mad.
I have a word. For each letter of the word, the characters position in one array is found and then returns the character at the same position found in a parallel array (basic cipher). This is what I already have:
*array 1 is the array to search through*
*array 2 is the array to match the index positions*
var character
var position
var newWord
for(var position=0; position < array1.length; position = position +1)
{
character = array1.charAt(count); *finds each characters positions*
position= array1.indexOf(character); *index position of each character from the 1st array*
newWord = array2[position]; *returns matching characters from 2nd array*
}
document.write(othertext + newWord); *returns new string*
The problem I have is that at the moment the function only writes out the last letter of the new word. I do want to add more text to the document.write, but if I place within the for loop it will write out the new word but also the other text inbetween each word. What i actually want to do is return the othertext + newWord rather than document.write so that I can use it later on. (just using doc.write to text my code) :-)
I know its something really simple, but I cant see where I am going wrong. Any advice?
Thanks
Issy
The solution is to build newWord within the loop using += instead of =. Just set it to an empty string before the loop.
There are other problems with this code. Variable count is never initialized. But let's assume that loops should be using count instead of position as it's principal counter. In that case, if I am not mistaken, this loop will just generate array2 as newWord. First two lines of loop's body cancel each other in a matter of speaking, and position will always be equal to count, so letters from array2 will be used sequentially from beginning to the end.
Could you provide one example of input and desired output, so that we understand what you actually want to accomplish?
A good way of structuring your code and your question is that you define a function that you need to implement. In your case this could look like:
function transcode(sourceAlphabet, destinationAlphabet, s) {
var newWord = "";
// TODO: write some code
return newWord;
}
That way, you clearly state what you want and which parameters are involved. It is also easy to write automatic tests later, for example:
function testTranscode(sourceAlphabet, destinationAlphabet, s, expected) {
var actual = transcode(sourceAlphabet, destinationAlphabet, s);
if (actual !== expected) {
document.writeln('<p class="error">FAIL: expected "' + expected + '", got "' + actual + '".</p>');
} else {
document.writeln('<p class="ok">OK: "' + actual + '".');
}
}
function test() {
testTranscode('abcdefgh', 'defghabc', 'ace', 'dfh');
}
test();