Conditional text change for div class - javascript

I have a list of grades on web page with identical span class. I Would need to append the current numeric grade and add a alphabet grade after the number. Current information is a text field and i would first need to parse the first 3 characters to identify the number. Then i would need to create a 5 level condition to give correct alphabet based on the number (example 0-40 = D, 40-60 = C, 60-80= B and 80-100 = A). Im newbie and just cant make it to work.
Grades list
I am able to update update the text, but when trying to parse and create conditions just was not able to make it work.
var elements = document.querySelectorAll('.score_value');
for ( var i=elements.length; i--; ) {
elements[i].textContent += "something else";
}
all the help would be appriciated

To parse integer in javascript, use parseInt() then include the parsed result in a condition to append what you want to text.

Related

Scan website for repeating keywords and create an array of it

I want to scan an website and filter out the most repeating keywords in the site.
If i would scan for example https://www.adidas.at/ then i would like to have an array with keywords like:
["clothing", "shoes", "pants", "t-shirt"]
and so on.
My idea was first to get all text content witch is inside of <body> with $eval() and split it up into an array and the use .reduce() and count how many times an word appears on the site and rank it.
Is this the way to go or is there an simple solution for it?
I would say the best approach would be to use page.evaluate(), and inside, acquire outerText of body which would return all the text content without the tags and stuff. After which you can convert the entire text to lower case(using toLowerCase()), and split the string on whitespaces or linebreaks or certain other symbols like brackets, etc. You can them keep count of repeated words using an object to store key values of word-count. So in essence your code would look like this:
let data = await page.evaluate(() => {
//acquire the text in body
let content = document.querySelector("body").outerText;
//convert text to lowercase and split on whitespaces and newlines
let textArray = content.toLowerCase().replace(/[^A-Za-z0-9]/gm, " ").split(/\s+/gm);
//object to map text to count
let text_to_count_map = {};
textArray.forEach(t => {
if(text_to_count_map[t])
text_to_count_map[t] ++;
else
text_to_count_map[t] = 1;
});
return text_to_count_map;
})
Now your data variable will contain an object of each word in the body as the key whose corresponding value would be their frequency in the body. You can do with it whatever you wish.
EDIT 1
Tested this on the Adidas site, and able to acquire all the words in the body into an array for textArray variable.
FINAL EDIT
Used a simpler regexp to filter anything that is not containing letters ([^A-Za-z0-9])

User list array filtering by containing the tag by RegExp in javascript

User list array filtering by containing the tag. I have an array of user list and I want to filter by tag contain using array filter match and RegExp for matching contain text its work but not get expected result.
let users=[{id:1,name:'john',tags:'a,b,c,v'},{id:2,name:'die',tags:'a,b,w,x'},{id:3,name:'ren',tags:'c,p,q,n'}];
let tagString='a,b,c';
let tagStringQuery = new RegExp(tagString, "i");
let data=users.filter((user) => user.tags.match(tagStringQuery)).map((user)=> user);
console.log('data',data);
O/P = [{id:1,name:'john',tags:'a,b,c,v'}]
but expected result is all user list which contains an 'a' or 'b' or 'c' tag.
This is really not a job for a regexp. Ideally you would have tags as Set instances, using intersection with a query Set to check for presence of tags.
If you insist on regexp though, you can't directly search for a,b,c to find if any of a, b or c is present: you would need to search for a|b|c (i.e. tagString.split(',').join('|')). If tags are of more than one letter, then you need to worry about substrings, so the search string should be \b(a|b|c)\b, and you should regexp-escape all the strings. And if you have multi-word tags or weird characters in them, you would need to search for ,(a|b|c), inside "," + user.tags + ",".
tagstring has to be 'a|b|c' instead of 'a,b,c' in case you want to apply or operator to those tags
Something like this should work fine without regex
let data = users.filter(x=>
tagString
.split(",")
.some(r=>
x.tags.split(",").includes(r)));

HTML5 form validation pattern automatically create a space after first 3 characters?

Using the pattern attribute in HTML forms is it possible to create a space automatically after 3 characters? How can this be accomplished?
pattern="([A-z0-9À-ž\s]){2,}"
The input is just a text field that receives the same data over and over. 3 numbers, 1 space, and then a name. I would like to be able to enter that but get back an extra space after the numbers.
For example:
If I enter: "951 Houston"I would like it to output: "951 Houston" <---extra space after the 3 numbers.
I would like it to be after any characters entered. So if someone were to enter "Houston" it would actually output "Hou ston" Is this possible using the pattern attribute in forms? If so how? If not what is a possible solution? Thanks
A regex can't add a space, so no, this is not possible with just HTML forms. What you would need to do is first extract the word to replace, then use a regex to split the word into a second word after three characters, then add the result back to the DOM:
var textareas = document.getElementsByTagName("textarea");
var str = document.getElementsByTagName("input")[0].value;
var replaced = str.replace(/.{3}/g, function (value, index) {
return value + (index % 5 == 0 ? ' ' : '');
});
textareas[0].value = replaced;
input, textarea {
width:100%
}
<input value="Houston"/>
<textarea></textarea>
In the above example, the string is extracted from the word in question (Houston in an input field, in this case), and replaced contains the string that has been broken into two new words. Simply insert it wherever you would like :)
Hope this helps! :)

How to get the line number based on substring in codemirror?

I need to get the line number of specific string in the textarea which has codemirror plugin.
var editor= CodeMirror.fromTextArea(document.getElementById("refstyle");
var doc = editor.getDoc();
var cursor = doc.getCursor(); // gets the line number in the cursor position
var line = doc.getLine(cursor.line); // get the line contents
editor.getSelection(line number) //it will select the text based on line number
So, How can I get the line number based on string (I expect something like doc.getLine(string) or doc.getSelection(String))
Is there any function to get the line number based on the string or to get searched string selected based on line number in the textarea? Pls help!
To search inside a CodeMirror instance, use the searchcursor addon. It'll give you the line/char position of matches.

Jquery data-target as string possible?

I have a data-attribute with a unique name and a number at the end.
data-target="foo-bar-n"
where n is the unique number.
I want to be able to get that number but it isn't working.
I call:
.data("target")
on the object I want the target from and It returns fine, but when I use a regex search on the results, I get a completely different number, which I suspect is because returned data is an object with other data. What I need to know is how to get that number out, or how to convert the data-attribute into a string. (I've tried toString, and that doesn't work.)
Here is my code:
var selection= window.getSelection().getRangeAt(0);
var showSelection = $(selection.commonAncestorContainer.parentNode.parentNode)
.data('target');
console.log(showSelection);
console.log(showSelection.search(/\d+/));
The console logs
#comment_for_paragraph_17
23
The program is meant to let a user select something on the page and highlight it.
If you are using jQuery 1.4.3 or later you can use
.data("target");
otherwise you must use
.attr("data-target");
But your requirement appears to be extracting a number from a formatted string parameter?
HTML:
<div id="foo" data-target="foo-bar-5"></div>
jQuery:
var num = $('#foo').data('target').split('-')[2];
Or regex:
var num = $('#foo').data('target').match(/\d+/);
Or if your requirement is specifically capture the last number in the string (eg: foo-bar-55-23 would result in '23')
var num = $('#foo').data('target').split('-').slice(-1);
// regex
var num = $('#foo').data('target').match(/\d+$/);
See fiddle
I suspect is because returned data is an object with other data.
That doesn't make any sense at all. The reason you are not getting the number in the string is because .search returns the index of the match. Use .match or .exec instead:
showSelection.match(/\d+/)[0];
/*or*/
/\d+/.exec(showSelection)[0];
Try:
.data('target').split('-').slice(-1)[0];
.split will split your string into an array with each array element being a word
.slice(-1) will return an array consisting of the last element of your array
[0] accesses the array element

Categories

Resources