I am to trying to extract numbers from string for example
East Texas Baptist University (582) (COL)
North Central Texas Academy (202471) (COL)
Bloomfield College (1662) (COL)
I have used parseInt but it gives me NAN. Can any one please suggest a better way. Thanks
You can use regex for that like:
"Bloomfield College (1662) (COL)".match(/(\d+)/)[0] //1662
Try this:
function getNumber(str) {
return parseInt(str.match(/\d+/)[0], 10);
}
You can use the function like this:
var num = getNumber('East Texas Baptist University (582) (COL)');
Related
I am trying to get 10 most frequent word in the sentence below, I need to use regular expression.
let paragraph = `I love teaching. If you do not love teaching what else can you love. I love Python if you do not love something which can give you all the capabilities to develop an application what else can you love.
I want an output like this
{word:'love', count:6},
{word:'you', count:5},
{word:'can', count:3},
{word:'what', count:2},
{word:'teaching', count:2},
{word:'not', count:2},
{word:'else', count:2},
{word:'do', count:2},
{word:'I', count:2},
{word:'which', count:1},
{word:'to', count:1},
{word:'the', count:1},
{word:'something', count:1},
{word:'if', count:1},
{word:'give', count:1},
{word:'develop',count:1},
{word:'capabilities',count:1},
{word:'application', count:1},
{word:'an',count:1},
{word:'all',count:1},
{word:'Python',count:1},
{word:'If',count:1}]```
This is a solution without regexp, but maybe it is also worth looking at?
const paragraph = `I love teaching. If you do not love teaching what else can you love. I love Python if you do not love something which can give you all the capabilities to develop an application what else can you love.`;
let res=Object.entries(
paragraph.toLowerCase()
.split(/[ .,;-]+/)
.reduce((a,c)=>(a[c]=(a[c]||0)+1,a), {})
).map(([k,v])=>({word:k,count:v})).sort((a,b)=>b.count-a.count)
console.log(res.slice(0,10)) // only get the 10 most frequent words
I have something a bit messy but it uses regex and displays top 10 of the highest occuring results which is what you asked for.
Test it and let me know if it works for you.
let paragraph = "I love teaching. If you do not love teaching what else can you love. I love Python if you do not love something which can give you all the capabilities to develop an application what else can you love.";
//remove periods, because teaching and teaching. will appear as different results set
paragraph = paragraph.split(".").join("");
//results array where results will be stored
var results = []
//separate each string from the paragraph
paragraph.split(" ").forEach((word) => {
const wordCount = paragraph.match(new RegExp(word,"g")).length
//concatenate the word to its occurence:: e.g I:3 ::meaning I has appeared 3 times
const res = word + " : " + wordCount;
//check if the word has been added to results
if(!results.includes(res)){
//if not, push
results.push(res)
}
})
function sortResultsByOccurences(resArray) {
//we use a sort function to sort our results into order: highest occurence to lowest
resArray.sort(function(a, b) {
///\D/g is regex that removes anything that's not a digit, so that we can sort by occurences instead of letters as well
return(parseInt(b.replace(/\D/g, ""), 10) -
parseInt(a.replace(/\D/g, ""), 10));
});
//10 means we are using a decimal number system
return(resArray);
}
//reassign results as sorted
results = sortResultsByOccurences(results);
for(let i = 0; i < 10; i++){//for loop is used to display top 10
console.log(results[i])
}
To get all words in a sentence use regular expressions:
/(\w+)(?=\s)/g.
If you use this in your input string then you get all words without the word which end with full-stop(.) i.e don't match the word "love.".
paragraph.match(/(\w+)(?=(\s|\.|\,|\;|\?))/gi)
So, in this case we have to modify the regex as:
/(\w+)(?=(\s|\.))/g.
Similarly, add the other special(,; ...) character which is end with some word.
This is your solution (please add the other special character if it's required).
let paragraph = `I love teaching. If you do not love teaching what else can you love. I love Python if you do not love something which can give you all the capabilities to develop an application what else can you love.`;
let objArr = [];
[...new Set(paragraph.match(/(\w+)(?=(\s|\.|\,|\;|\?))/gi))].forEach(ele => {
objArr.push({
'word': ele,
'count': paragraph.match(new RegExp(ele+'(?=(\\s|\\.|\\,|\\;|\\?))', 'gi'))?.length
})
});
objArr.sort((x,y) => y.count - x.count);
I tried to do it but didn't work
I want to achieve something like this:
function clubMember(clubName, women + men, women, men) {
const club = `${clubName} club has ${women + men} members including ${women} Women and ${men} Men`
return club
}
The answer is: no, you can't put arithmetic operators as a parameter.
As far as I know, there are no languages that gives you ability to calculate as a parameter.
However, you could do something like this if you wish:
function clubMember(clubName, total, women, men) {
const club = `${clubName} club has ${total} members including ${women} Women and ${men} Men`;
return club;
}
clubMember(club, women+men, women, men);
So this is my code
if (body.included != null && body.included.length > 0) {
let genres = '';
for(let i = 0; i < body.included.length; i++) {
genres += body.included[i].attributes.title;
if(i != body.included.length - 1) {genres += ', ';}
}
embed.addField('GENRES', [`${genres}`,], true);
}
this is the results whenever i search anything with this it gives me this:
Comedy, Kids, Fantasy, Fantasy World, Erotic Torture, Loli, Nudity, Bdsm, Bondage, Sex, Past, Plot Continuity, Violence, Military, Mecha, Historical, Action, Romance, Science Fiction, World War II, Japan, Asia, Piloted Robot, Alternative Past, Steampunk, Gunfights, Alien, War, Robot, Adventure, Space Travel, Cyborg, Crime, Other Planet, Humanoid Alien, Future, Space, Contemporary Fantasy, Vampire, Slice of Life, Detective, Bounty Hunter, Magic, Present, Demon, Super Power, Drama, Anime Influenced, Earth, Love Polygon, Angst, High School, School Life
Has this a example because other types searches comes with 1 or 2 or decent amount of genres where it doesn't have like 40 of them
like this one
Ninja, Fantasy World, Adventure, Action, Comedy, Martial Arts, Super Power, Romance, Disaster, Shounen, Love Polygon, Angst, Plot Continuity, Parallel Universe, Fantasy
So what i need help is how do i make it stop in a certain number where it wont give me 40 of them instead 10 or less
You could change the loop condition but still need to watch out for the length of the body.included array for cases where it has fewer than 10 elements. Try the following:
const MAX_GENRES = 10;
if (body.included && body.included.length) {
const max = Math.min(MAX_GENRES, body.included.length);
const genres = [];
let i = 0;
while (i < max) {
genres.push(body.included[i].attributes.title);
i += 1;
}
embed.addField('GENRES', [genres.join(',')], true);
}
This should achieve what you're after. I don't know the signature for embed.addField() but are you certain that the second argument should be a single-element array containing a string? Could be but seems weird. If the function calls for an array of strings use:
embed.addField('GENRES', genres, true);
As part of an assignment for uni i've been asked to write a question worth 10 marks and then write a solution and marking scheme for said question.
This is my question;
Write a program that will store the top ranking fighters of 3 weight divisions in the UFC (using the following data);
-Featherweight; Connor McGregor, Jose Aldo, Frankie Edgar, Max Holloway, Anthony Pettis.
-Lightweight; Connor McGregor, Khabib Nurmagomedov, Tony Ferguson, Eddie Alvarez, Rafael dos Anjos.
-Light heavyweight; Daniel Cormier, Anthony Johnson, Alexander Gustafsson, Ryan Bader, Glover Teixiera.
Prompt the user to enter the name of a weight division in the UFC and return the ranking the the format;
Current Champion is ….
1st contender is …..
2nd contender is ……
Etc.
So far in my solution for the questioni have had the user enter the name of a weight division, however i now have the problem of trying to use that specific variable in a loop.
This is my code so far;
//Declaration of the arrays to store the ranking of the weight divisions;
var featherweight = ["Connor McGregor", "Jose Aldo", "Frankie Edgar", "Max Holloway", "Anthony Pettis"];
var lightweight = ["Connor McGregor", "Khabib Nurmagomedov", "Tony Ferguson", "Eddie Alarez", "Rafael dos Anjos"];
var lightHeavyweight = ["Daniel Cormier", "Anthony Johnson", "Alexander Gustafsson", "Ryan Bader", "Glovier Teixiera"];
//Declaring the output variable to store and add to what will be output before it is displayed;
var output = "";
//Variable to store the user input and a prompt to recieve the users input;
var userInput = prompt("Please enter the name of a weight devision you would like to see the rankings off. \n Options are; \n - featherweight \n - lightweight \n - lightHeavyweight");
//loop that will continue adding items to the output for the length of the array that the user has asked to see.;
for (var i = 0; i < )
Help is greatly appreciated, and thanks in advance!
Before the loop you should have chained if statements:
var chosenArray;
if (input === "x")
{
chosenArray = xArray;
}
elseif (input === "y")
{
chosenArray = yArray;
}
...
else
{
// should print that the input is unknown
}
// should use chosenArray for loop
I'm trying to understand how to user parseFloat to convert a string to a number--which by the way changes based on a users rewards club points.
Here's the code I've written so far:
var ptsBalance = jQuery('.value.large.withCommas').text(); // get current RC points balance
var strParse = parseInt(ptsBalance, 10); // * Output should be current RC balance
alert(strParse); // alert Rewards Club Balance
var bonusPoints = 70000;
var totalPts = jQuery(strParse + bonusPoints); // sum total of Bonus and Current points
jQuery(strParse).appendTo('.currentPts');
jQuery(totalPts).appendTo('.totalPts'); // insert RC points balance after 'Current Points' text
Clearly I'm not using pareFloat, but rather strParse, which is rounding my string. That said, how do I convert a string to a number that could be "10", "100", "1,000", "10,000" etc.?
Here's a link to my Fiddle: http://jsfiddle.net/bkmills1/60vdfykq/
Still learning...
Thanks in advance!
In your fiddle, change line 4 from:
var strParse = parseInt(ptsBalance, 10);
to
var strParse = parseInt(ptsBalance.replace(',',''), 10);
You may also want to remove any other symbols needed, or even use regular expressions to do just that.