Guide on word occurrence in a textarea - javascript

I have a Textarea box, a textbox and a button. I would like on clicking the button, for the word in the textbox to be checked against words in the textarea and count number of occurrence.
I have tried last 2 days to write a click function to do this but not getting anywhere since not sure what codes or logic follows next. Only managed to read the contents in the textarea but not sure how to get the word in the textbox and search against sentence in textarea.
Please I am a newbie in JQuery so not asking for anyone to write the code but more of a guide if possible. If this question isn't permitted here, I am more than happy to delete it. Thanks

Use string.match() along with processing to ensure the first string is not empty and that there actually is a match. Did the following in jQuery since you seemed interested in using it.
var textVal = $('#textbox').val();
var textArea = $('#textarea').val();
var matching = new RegExp('\\b' + textVal + '\\b','g');
var count = textArea.match(matching);
var result = 0;
if (count !== null) {
result = count.length;
}
http://jsfiddle.net/promiseofcake/t8Lg9/3/

You are looking for string occurrences, so take a look at this thread.
You could do this using match(), as suggested in the comments:
var m = searchText.match(new RegExp(wordMatch.toString().replace(/(?=[.\\+*?[^\]$(){}\|])/g, "\\"), "ig"));
// m.length contains number of matches
But that will also match partial words, like 'fox' in 'foxy'. So another method is to split the input into words and walk over them one by one:
var count = 0;
var words = searchText.split(' ');
for (x in words) {
if (words[x].toLowerCase() == wordMatch) {
count++;
}
}
Take a look at this full example: http://jsfiddle.net/z7vzb/

<input type="text"/>
<textarea>...</textarea>
<button>Get</button>
<div></div>
<script>
$("button").click(function(){
count=$("textarea").text().split($("input[type=text]").val()).length-1;
$("div").html(count);
})
</script>

Related

Finding multiple groups in one string

Figure the following string, it's a list of html a separated by commas. How to get a list of {href,title} that are between 'start' and 'end'?
not thisstartfoo, barendnot this
The following regex give only the last iteration of a.
/start((?:<a href="(?<href>.*?)" title="(?<title>.*?)">.*?<\/a>(?:, )?)+)end/g
How to have all the list?
This should give you what you need.
https://regex101.com/r/isYIeR/1
/(?:start)*(?:<a href=(?<href>.*?)\s+title=(?<title>.*?)>.*?<\/a>)+(?:,|end)
UPDATE
This does not meet the requirement.
The Returned Value for a Given Group is the Last One Captured
I do not think this can be done in one regex match. Here is a javascript solution with 2 regex matches to get a list of {href, title}
var sample='startfoo, bar,barendstart<img> something end\n' +
'beginfoo, bar,barend\n'+
'startfoo again, bar again,bar2 againend';
var reg = /start((?:\s*<a href=.*?\s+title=.*?>.*?<\/a>,?)+)end/gi;
var regex2 = /href=(?<href>.*?)\s+title=(?<title>.*?)>/gi;
var step1, step2 ;
var hrefList = [];
while( (step1 = reg.exec(sample)) !== null) {
while((step2 = regex2.exec(step1[1])) !== null) {
hrefList.push({href:step2.groups["href"], title:step2.groups["title"]});
}
}
console.log(hrefList);
If the format is constant - ie only href and title for each tag, you can use this regex to find a string which is not "", and has " and a space or < after it using lookahead (regex101):
const str = 'startfoo, barend';
const result = str.match(/[^"]+(?="[\s>])/gi);
console.log(result);
This regex:
<.*?>
removes all html tags
so for example
<h1>1. This is a title </h1><ul><a href='www.google.com'>2. Click here </a></ul>
After using regex you will get:
1. This is a title 2. Click here
Not sure if this answers your question though.

Create a text area and analyze button

I am working on my college homework. I am having a lot of difficulty with it and getting stuck. My class mates are not helping me and the instructor hasn't responded. I am hoping I might get some help/understanding here. The current assignment I am working on and it is due today is:
Create a page containing a textarea and an “analyze” button. The results area will display the frequency of words of x characters. For example, the text “one two three” contains 2 3-character words and 1 5-character word. An improvement to the original design would be to strip out any extraneous characters that may skew the count.
I am just starting it now, so I will add the code here as I update. I know I won't have a problem with the HTML part, the JavaScript will be my problem. From what I get, I will need to have a function that counts the words and the characters in each word. But it needs to exclude spaces and characters like: ,.';/. I have not run across this code before, so any input on how I should frame the javascript will be helpful. Also it seems he wants me to list how many words have the same characters? am I reading this right?
My code thus far:
<!DOCTYPE html>
<html>
<body>
<textarea id="txtarea">
</textarea>
<input type="button" id="analyze" value="Analyze" onclick="myFunction()" />
<p id="demo"></p>
<p id="wcnt"></p>
<script>
function myFunction() {
var str = document.getElementById("txtarea").value;
var res = str.split(/[\s\/\.;,\-0-9]/);
var n = str.length;
document.getElementById("demo").innerHTML = "There are " + n + " characters in the text area.";
for (var i = 0; i < res.length; i++) {
s = document.getElementById("txtarea").value;
s = s.replace(/(^\s*)|(\s*$)/gi, "");
s = s.replace(/[ ]{2,}/gi, " ");
s = s.replace(/\n /, "\n");
document.getElementById("wcnt").innerHTML = "There are " + s.split(' ').length + " words in the text area.";
}
}
</script>
</body>
</html>
Now I need to figure out how to make it count the characters of each word then output how many words have x amount of characters. Such as 5 words have 4 characters and so on. Any suggestions?
var textarea = document.getElementById("textarea"),
result = {}; // object Literal to hold "word":NumberOfOccurrences
function analyzeFrequency() {
// Match/extract words (accounting for apostrophes)
var words = textarea.value.match(/[\w']+/g); // Array of words
// Loop words Array
for(var i=0; i<words.length; i++) {
var word = words[i];
// Increment if exists OR assign value of 1
result[word] = ++result[word] || 1;
}
console.log( result );
}
analyzeFrequency(); // TODO: Do this on some button click
<textarea id="textarea">
I am working on my college-homework.
Homework I am having a lot of difficulty with it and getting stuck.
My class mates are not helping me and the instructor hasn't responded.
I am hoping I might get some help/understanding here.
</textarea>
Notice how Homework and homework (lowercase) are registered as two different words, I'll leave it to you to fix that - if necessary and implement the analyzeFrequency() trigger on some button click.
Most likely you will have to use JavaScript's split function with regex to define all the characters you do not want to include. Then loop through the resulting array and count the characters in each word.
var words = document.getElementById("words");
var analyze = document.getElementById("analyze");
analyze.addEventListener("click", function(e) {
var str = words.value;
var res = str.split(/[\s\/\.;,\-0-9]/);
for(var i = 0; i < res.length; i++) {
alert(res[i].length);
}
});
<textarea id="words">This is a test of this word counter thing.</textarea>
<br/>
<button id="analyze">
Analyze
</button>
Your instructor does NOT want you to list how may words have the same characters but rather the same number of characters. The basic algorithm:
Assign the value of the text area to a variable.
Convert that string value into an array. In javascript this could be accomplished with the String split method using a regular expression containing a character class.
Iterate over that array examining each element for its length. For each element, increment a counting object's property whose property name is the length of the element.
Iterate over the counting object's property list. Output to the result area each property name and its value.

Trim a variable's value until it reaches to a certain character

so my idea is like this..
var songList = ["1. somesong.mid","13. abcdef.mid","153. acde.mid"];
var newString = myString.substr(4); // i want this to dynamically trim the numbers till it has reached the .
// but i wanted the 1. 13. 153. and so on removed.
// i have more value's in my array with different 'numbers' in the beginning
so im having trouble with this can anyone help me find a more simple solution which dynamically chop's down the first character's till the '.' ?
You can do something like
var songList = ["1. somesong.mid","13. abcdef.mid","153. acde.mid"];
songList.forEach(function(value, i){
songList[i] = value.replace(/\d+\./, ''); //value.substr(value.indexOf('.') + 1)
});
Demo: Fiddle
You can use the string .match() method to extract the part up to and including the first . as follows:
var newString = myString.match(/[^.]*./)[0];
That assumes that there will be a match. If you need to allow for no match occurring then perhaps:
var newString = (myString.match(/[^.]*./) || [myString])[0];
If you're saying you want to remove the numbers and keep the rest of the string, then a simple .replace() will do it:
var newString = myString.replace(/^[^.]*. */, "");

how to check a variable is having nextline or not in javascript

i have a wrote one js program so that it will accept the user input from a textfield and then it the program automatically make that user input in to the screen like a status in fb.
in that if i gave that input and when it is displaying the next line sentence is appended to the before sentence.
how can i check that one and correct that mistake?
Thanks in advance.
In a very simple way, this problem can be solved using the indexOf method.
var text = textarea.innerHTML;
if(text.indexOf('\n') !== -1) {
// the text contains a new line
}
The indexOf method returns the index of the expression or -1 if it isn't found.
var text = $("#theTextArea").val();
var match = /.*\r|.*\n/.exec(text);
if (match) {
// Found .. the text area has a sentence already.
}
Check out this fiddle
var x = "Some text\n here";
var patt1 = /\n/;
alert(x);
if(x.search(patt1) > 0)
alert("New line character present");
else
alert("New line character not present");

To count number of spaces using jquery?

Question: I need a solution to find number of empty spaces infront of checkbox inside list tag by using jquery
<li id='list_id'>
<input type="checkbox" name="check">good
</li>
var listItem = $('#list_id');
var clone = listItem.clone();
clone.find('*').remove();
matches = clone.html().match(/ /g);
alert(matches.length);
That will alert() the number of in the text node of #list_id.
See it on jsFiddle.
Though, if you only want leading ones before anything else, try this...
var listItem = $('#list_id');
var html = $.trim(listItem.html());
var count = 0;
var match = ' ';
while (html.substr(0, match.length) === match) {
count++;
html = html.substr(count * match.length, (count * match.length) + match.length);
}
alert(count);
See it on jsFiddle.
That will count all end-on-end, i.e. glued together. If you'd just like to match every one before the opening angle bracket, Lee has a solution available on jsFiddle.
var elemntArr=$('#list_id.).html().split(" ")
from the above arrary you can count empty spaces

Categories

Resources