I am working on a project that takes text that a user inputs in a text box and returns the most common word.
Javascript:
var bestMode = 1;
var currentMode = 0;
var character;
function Find_Word(){
var words = document.getElementById('words').innerText;
var punctuationless = words.replace(/['!"#$%&\\'()\*+,\-\.\/:;<=>?#\[\\\]\^_`{|}~']/g,"");
var finalString = punctuationless.replace(/\s{2,}/g," ");
var WordList = finalString.split(" ");
return FindMode(WordList);
}
function FindMode(WordList){
for(var i=0; i<WordList.length; i++){
for(var m=i; m<WordList.length; m++){
if(WordList[i] == WordList[m]){
currentMode += 1;
}
if(bestMode<currentMode){
bestMode = currentMode;
character = WordList[i];
}
}
currentMode = 0;
}
}
console.log(bestMode);
HTML:
<html>
<body>
<h1>Most common word used</h1>
<input type="text" id="words" rows="10" columns="30"></input>
<button type="button" id="FindWord" onclick="Find_Word()">Find Word</button>
<script src="CommonWord.js"> </script>
</body>
</html>
What I can't figure out is the correct way to pull text from the text box into a variable as one string. My function Find_Word takes the received string when the button is pressed and strips away punctuation and leaves an array WordList with with each individual word in the string.
After that, I also can't understand how to pass that array into my second function findMode where I iterate through each value of the array to find the most common word. That is saved in the variable bestMode.
It looks as if you are both getting the current text and passing the array correctly (although perhaps you should get the textbox value using the .value property). What problem are you having exactly? I am not sure what FindMode is supposed to do either.
Here is some script that is based on what you posted that sorts "words" according to how often they appear :
(function(w) {
w.Sort_Words = function(words) {
var o = {}, l = [];
for(var i=0; i<words.length; i++) {
if (typeof o[words[i]] === 'undefined') {
o[words[i]] = 0;
l.push(words[i]);
}
o[words[i]] ++;
}
l.sort(function(a, b) { return o[b] - o[a]; });
return l;
};
w.Find_Word = function() {
var text = document.getElementById('words').value;
var words = text.replace(/['!"#$%&\\'()\*+,\-\.\/:;<=>?#\[\\\]\^_`{|}~']/g,"").replace(/\s{2,}/g," ").split(' ');
var sorted = w.Sort_Words(words);
document.getElementById('results').innerText = sorted.length === 0 ?
'You must type at least one word' :
'The most commonly used word was: ' + sorted[0];
};
})(window);
Fiddler: http://jsfiddle.net/4u1mv20h/4/
Related
There is a string that may contain nicknames given by #nickname. Nickname can be inputed by user with typo by concatenation with previous word, like
Hello my inst is#nickname
Also nickname word can be situated at the beginning of the new paragraph, hence just using split(' ') wouldn’t work.
What I want ultimately do is to after user inputs, highlight nicknames in string by covering them with <span> setting some styles and adding onclick link to instagram with that account.
Solution I’ve made so far:
<script>
window.onload=function()
{
var text = "Hello #buf world #text";
text = Synt(text);
var a = addP(document.body,text,30,30,"black",20);
a.innerHTML=text;
}
function Synt(a)
{
if(a.search('#')==-1)
return a;
else
{
var regex = /#/gi, result, indices = [];
while ( (result = regex.exec(a)) ) {
indices.push(result.index);
}
var a1 = (' ' + a).slice(1);
var ar = a.split('');
for(var i=0;i<indices.length;i++)
{
var r=[];
var rr=0;
for(var j=indices[i];j<a.length&&(isLetter(a[j])||a[j]=='.'||a[j]=='_'||rr==0);rr++,j++)
r[rr]=a[j];
r=r.join('');
a1 = a1.replace(r,'<span style="color:blue">'+r+'</span>');
}
return a1;
}
}
function isLetter(str) {
return str.length === 1 && str.match(/[a-z|0-9]/i);
}
function addP(par,text,left,top,color='black',size='17px', fun=0)
{
var p = document.createElement('p');
p.style.position = 'absolute';
p.style.color=color
p.style.fontSize=size;
p.style.fontFamily='Arial';
par.appendChild(p);
p.style.left=left;
p.style.top=top;
p.innerText=text;
if(fun)
p.onclick=fun;
return p;
}
</script>
Please I have two arrays
Var subject("goat","man");
Var predicate ("enter", "come");
I want to make a search page that will display the results if the input items matches the two arrays
Please help
var subject = ['goat','man'];
var predicate = ['enter', 'come'];
var i;
function my_func(){
var search_value = document.getElementById('search1').value; //the entered value in the searchbox
for(i = 0; i < subject.length && predicate.length; i++){ //Find the item that you enter in searchbox
if(search_value === subject[i]){ //
document.getElementById('demo').innerHTML = subject[i];
}
if(search_value === predicate[i]){
document.getElementById('demo').innerHTML = predicate[i];
}
}
}
<input type="search" id="search1"> <button onclick = "my_func()">Show</button>
<p id="demo"></p>
In a webpage there is a textarea (id="text") and also a button (id="dlButton3").
What I have to do is to enter the text into the textarea. And when I press the button, then the following will be happened:
Text in the text area will be loaded into the function,
The text will be spitted with delimiters ""
There is a for loop to compare all the lengths of the strings, and
Print the longest one value
The problem is, with the following code, I can take the string from the text area but dun know why I cannot split the string, and it returns the error "Uncaught ReferenceError: targetString is not defined"
The code is as followed
function findlongestword(){
var testing = document.getElementById('text').value;
console.log(testing);
var strText = testing.split(" ");
var length = 0;
for (var i=0; i < strText.length; i++) {
if (length < strText[i].length) {
length = strText[i].length;
targetString = strText[i]
}
}
console.log (targetString);
}
window.onload = function(){
findlongestword();
document.getElementById("dlButton3").onclick = findlongestword;
}
What can be the error?
Many thanks for your help in advance!
Read more about block scope targetString only exists within the loop
function findlongestword() {
var testing = document.getElementById('text').value;
var strText = testing.split(" ");
var length = 0;
var targetString = '';
for (var i=0; i < strText.length; i++) {
if (length < strText[i].length) {
length = strText[i].length;
targetString = strText[i]
}
}
console.log (targetString);
}
window.onload = function() {
findlongestword();
document.getElementById("dlButton3").onclick = findlongestword;
}
"Uncaught ReferenceError: targetString is not defined"
You did not declare targetString before using it within your loop. Therefore javascript did not know where to find or 'Refer' to it after the loop ended.
By adding var targetString = ""; before the loop begins the problem will be solved.
function findlongestword(){
var testing = document.getElementById('text').value;
console.log(testing);
var strText = testing.split(" ");
//ADD HERE
var targetString = "";
var length = 0;
for (var i=0; i < strText.length; i++) {
if (length < strText[i].length) {
length = strText[i].length;
targetString = strText[i]
}
}
console.log (targetString);
}
window.onload = function(){
findlongestword();
document.getElementById("dlButton3").onclick = findlongestword;
}
I have a html textarea and i need to extract the word from the text in it, depending on where the caret is.
So, if the caret is in a word, or just at the end of beginning (or end) of a word, i need to get that.
How can i do that? Im not looking for a library, just plain javascript.
Please help.
Here is some code that will do the job. Basically, extract the caret position. Convert sentence to array. Loop array adding words lengths together, when length is greater than caret position you have found your word.
<html>
<script>
function getCaret(node) {
if (node.selectionStart) {
return node.selectionStart;
} else if (!document.selection) {
return 0;
}
var c = "\001",
sel = document.selection.createRange(),
dul = sel.duplicate(),
len = 0;
dul.moveToElementText(node);
sel.text = c;
len = dul.text.indexOf(c);
sel.moveStart('character',-1);
sel.text = "";
return len;
}
function getWord()
{
var el = document.getElementById('myText');
var carret = getCaret(el);
var words = el.value.split(' ');
var x = 0;
for(var i = 0; i < words.length; i++)
{
debugger;
x += words[i].length + 1;
if(x > carret){ return words[i]; }
}
}
function myWord()
{
var word = getWord();
alert(word);
}
</script>
<body>
<button onclick="myWord();" >Get word</button>
<textarea id="myText">This is a hallo world sentence</textarea>
</body>
</html>
I have a text array. I want to display the first entry on page load. And then replace the text with the next entry when I click a button. If I keep clicking the button I want the text to continuously be replaced by waht is next in the array, and when it gets to the end start back at the first entry. Can someone please show me an example code for that. I am new to this.
Here's what I have
$(document).ready(function(){
var arr = new Array("One","Two","Three");
var len=arr.length;
$('#next').click(function(){
for(var i=0; i<len; i++) {
$('#quote').html(arr[i]);
}
});
});
Something like the following should do the trick:
<script type="text/javascript">
var nextWord = (function() {
var wordArray = ['fe','fi','fo','fum'];
var count = -1;
return function() {
return wordArray[++count % wordArray.length];
}
}());
</script>
<p id="foo"> </p>
<button onclick="
document.getElementById('foo').innerHTML = nextWord();
">Update</button>
Edit
Radomised version:
var nextWord = (function() {
var wordArray = ['fe','fi','fo','fum'];
var copy;
return function() {
if (!copy || !copy.length) copy = wordArray.slice();
return copy.splice(Math.random() * copy.length | 0, 1);
}
}());
The following should do it http://jsfiddle.net/mendesjuan/9jERn/1
$(document).ready(function(){
var arr = ["One","Two","Three"];
var index = 0;
$('#next').click(function(){
$('#quote').html(arr[index]);
index = (index + 1) % arr.length ;
});
});
Your code was writing all three values each time you clicked it (but only displaying that last value)
I think something like this would work
The javascript would look like:
// assuming maxTextArrayIndex & textArray are defined & populated
var textDisplayIndex = -1;
document.getElementById('textDisplay').innerHTML = textArray[textDisplayIndex];
function nextElement()
{
textDisplayIndex += 1;
if (textDisplayIndex > maxTextArrayIndex)
{
textDisplayIndex = 0;
}
document.getElementById('textDisplay').innerHTML = textArray[textDisplayIndex];
}
The html would look like:
<body onLoad=nextElement()>
...
<elementToDisplayText id=textDisplay></elementToDisplayText>
<button onClick=nextElement()>Next</button>