Ignore words less than or equal 3 javascript array - javascript

I'm building my own boorkmarklet for analyze the words in the current page, currently it's working good, but I would like filter the words and just show the words longer than 3 letters, I'm new with javascript but here is my code:
var sWords = document.body.innerText.toLowerCase().trim().replace(/[,;.]/g,'').split(/[\s\/]+/g).sort();
// count duplicates
var iWordsCount = sWords.length;
// array of words to ignore
var ignore = ['and','the','to','a','of','for','as','i','with','it','is','on','that','this','can','in','be','has','if'];
ignore = (function(){
var o = {};
var iCount = ignore.length;
for (var i=0;i<iCount;i++){
o[ignore[i]] = true;
}
return o;
}());
thanks for the time !

You can use filter function :
function greaterThanThree(element){
return element.length > 3;
}
var longer_words = ['f','as','i','with','on','that','this','can','has','if'].filter(greaterThanThree);
//Will return ["with", "that", "this"]
Hope this helps.

Related

Set the last number in a string to negative

I have a string with diffrent mathematical characters, and i want to make the last number negative/positive. Let's say the string is "100/5*30-60+333". The result i want is "100/5*30-60+(-333)", and i want to convert it back to positive ("100/5*30-60+333").
function posNeg() {
// hiddenText is a <input> element. This is not shown.
let n = hiddenText.value;
n.split('+');
n.split('-');
n.split('*');
n.split('/');
console.log(n);
}
What i get is the whole hiddenText.value, and not an array of all numbers. Any tips?
First, I'd match all of the basic math operators to get their order:
const operatorsArr = n.match(/\+|\-|\/|\*/g)
Then, split the string:
function posNeg() {
// hiddenText is a <input> element. This is not shown.
let n = hiddenText.value;
n = n.replace(/\+|\-|\/|\*/g, '|');
n = n.split('|');
console.log(n);
}
Then, you will have an array of numbers, in which you can mutate the last number easily:
n[n.lengh-1] *= -1;
Now we can combine the two arrays together:
let newArr;
for (let i = 0; i < n.length; i++) {
newArr.push(n[i]);
if (operatorsArr[i]) newArr.push(operatorsArr[i]);
}
At last, you can rejoin the array to create the new String with a seperator of your choosing. In this example I'm using a space:
newArr = newArr.join(' ')
Please let me know how that works out for you.
Let's say the string is "100/5*30-60+333". The result i want is
"100/5*30-60+(-333)", and i want to convert it back to positive
("100/5*30-60+333").
The following code does that:
let mathStr = '100/5*30-60+333';
console.log(mathStr);
let tokens = mathStr.split('+');
let index = tokens.length - 1;
let lastToken = tokens[index];
lastToken = '('.concat('-', lastToken, ')');
let newMathStr = tokens[0].concat('+', lastToken);
console.log(newMathStr); // 100/5*30-60+(-333)
console.log(mathStr); // 100/5*30-60+333
EDIT:
... and i want to convert it back to positive ("100/5*30-60+333").
One way is to declare mathStr (with the value "100/5*30-60+333") as a var at the beginning and reuse it, later as you need. Another way is to code as follows:
let str = "100/5*30-60+(-333)";
str = str.replace('(-', '').replace(')', '');
console.log(str); // 100/5*30-60+333
To get numbers You can use replace function and split check code bellow :
function posNeg() {
// hiddenText is a <input> element. This is not shown.
let n = "100/5*30-60+333";
n = n.replace('+','|+');
n = n.replace('-','|-');
n = n.replace('*','|*');
n = n.replace('/','|/');
n=n.split('|');console.log(n);
// to use any caracter from array use it in removeop like example
// if we have array (split return) have 100 5 30 60 333 we get 100 for example
// we need to make removeop(n[0]) and that reutrn 100;
// ok now to replace last value to negative in string you can just make
// var lastv=n[n.length-1];
// n[n.length-1] ='(-'+n[n.length-1])+')';
//var newstring=n.join('');
//n[n.length-1]=lastv;
//var oldstring=n.join('');
}
function removeop(stringop)
{
stringop = stringop.replace('+','');
stringop = stringop.replace('-','');
stringop = stringop.replace('*','');
stringop = stringop.replace('/','');
return stringop;
}
If you really need to add "()", then you can modify accordingly
<script>
function myConversion(){
var str = "100/5*30-60-333";
var p = str.lastIndexOf("+");
if(p>-1)
{
str = str.replaceAt(p,"-");
}
else
{
var n = str.lastIndexOf("-");
if(n>-1)
str = str.replaceAt(n,"+");
}
console.log(str);
}
String.prototype.replaceAt=function(index, replacement) {
return this.substr(0, index) + replacement+ this.substr(index + replacement.length);
}
</script>

Capture respective index of same string with multiple occurences using Javascript

input
Lets go to play football.
I love football.
Here, how do I get the respective start and end index of both the first 'football' and the second 'football'?
var start_index = input.indexOf('football');
This only gives me the index of the first occurence of football .
You can use this function that will find every occurence.
const s = 'Lets go to play football.\n' +
'I love football.';
const findIndices = (s, word) => {
let index = -1;
while(1) {
index = s.indexOf(word, index + 1);
if (index === -1) return;
console.log(index);
}
};
findIndices(s, 'football');
One option is using RegExp.prototype.exec function:
var str = "Lets go to play football.\nI love football.";
var reg = /football/g, indices = [];
while (reg.exec(str) !== null) {
indices.push(reg.lastIndex - reg.source.length);
}
// indices:
// Array(2)
// 0: 16
// 1: 33
In the above code str is the input and indices is an array of indices (indexes).
A good place to find out about these kind of things is the documentation indexOf()
As you can see, this function accepts a second parameter that is used to determine form where to start the search.
That means that you can get the index of the second occurrence like this:
var str = "Lets go to play football.\nI love football.";
var firstIndex = str.indexOf("football");
var secondIndex = str.indexOf("football", firstIndex + 1);
console.log(firstIndex, secondIndex);
And to do that for all the occurrences, you can use a loop:
var str = "Lets go to play football.\nI love football.\nI love football.";
var indexes = [];
var latestIndex = -1;
while(true){
latestIndex = str.indexOf("football", latestIndex + 1);
if(latestIndex === -1){
break;
}
indexes.push(latestIndex);
}
console.log(indexes);

Counting the frequency of elements in an array in JavaScript

how do I count the frequency of the elements in the array, I'm new to Javascript and completely lost, I have looked at other answers here but can't get them to work for me. Any help is much appreciated.
function getText() {
var userText;
userText = document.InputForm.MyTextBox.value; //get text as string
alphaOnly(userText);
}
function alphaOnly(userText) {
var nuText = userText;
//result = nuText.split("");
var alphaCheck = /[a-zA-Z]/g; //using RegExp create variable to have only alphabetic characters
var alphaResult = nuText.match(alphaCheck); //get object with only alphabetic matches from original string
alphaResult.sort();
var result = freqLet(alphaResult);
document.write(countlist);
}
function freqLet(alphaResult) {
count = 0;
countlist = {
alphaResult: count
};
for (i = 0; i < alphaResult.length; i++) {
if (alphaResult[i] in alphaResult)
count[i] ++;
}
return countlist;
}
To count frequencies you should use an object which properties correspond to the letters occurring in your input string.
Also before incrementing the value of the property you should previously check whether this property exists or not.
function freqLet (alphaResult) {
var count = {};
countlist = {alphaResult:count};
for (i = 0; i < alphaResult.length; i++) {
var character = alphaResult.charAt(i);
if (count[character]) {
count[character]++;
} else {
count[character] = 1;
}
}
return countlist;
}
If you can use a third party library, underscore.js provides a function "countBy" that does pretty much exactly what you want.
_.countBy(userText, function(character) {
return character;
});
This should return an associative array of characters in the collection mapped to a count.
Then you could filter the keys of that object to the limited character set you need, again, using underscore or whatever method you like.
Do as below:
var __arr = [6,7,1,2,3,3,4,5,5,5]
function __freq(__arr){
var a = [], b = [], prev
__arr.sort((a,b)=>{return a- b} )
for(let i = 0; i<__arr.length; i++){
if(__arr[i] !== prev){
a.push(__arr[i])
b.push(1)
}else{
b[b.length - 1]++
}
prev = __arr[i]
}
return [a , b]
}

Counting up within a function of Javascript.

I have the following javascript code:
nback.lightElement = function(index) {
var letterArray = new Array('Lorem', 'Ipsum' , 'Dolor', 'Est');
var r = Math.floor(Math.random()*4);
var letter = letterArray[r];
nback.numbers[index] = letter;
nback.numbers.innerHTML = letter;
nback.litCell = letter;
nback.current = letter;
nback.previous.push(nback.current);
};
nback.startGame = function() {
nback.round += 1;
nback.updateRound();
nback.blink_count = 0;
// Make a new game
nback.queue = new Queue();
for (i = 0; i < BLINKS; i++) {
// Populate with random data, less fun than created games
// but this is way easier to program.
nback.queue.queue(Math.floor(Math.random() * 1));
}
// Run the game loop every TIME_BETWEEN_ROUNDS
nback.intervalId = window.setInterval(nback.next, TIME_BETWEEN_BLINKS);
};
This gives my a random word output from the letterArray for TIME_BETWEEN_BLINKS milliseconds (e.g. 1000). That word is shown for 1000ms, disappears, and another word appears randomly. This loops BLINKS-times.
Now I do not want it to choose random words from the letterArray (the var r = Math.floor(Math.random()*4); is one of my main concerns). It should just show them one after another. I tried so many different approches (mainly loops of every kind) but still can't make it work. Most of the time I tried loops I got "undefined" (instead of the actual words) or just nothing (blank).
I use https://github.com/chuckha/N-back as a reference.
Help will be much appreciated.
You can use an index for that array that is initialized outside of the function. Here is some code that gives the next word from the array whenever the lightElement function gets called. It also wraps around.
var letterArrayIndex=0;
nback.lightElement = function(index) {
var letterArray = new Array('Lorem', 'Ipsum' , 'Dolor', 'Est');
var letter = letterArray[letterArrayIndex];
letterArrayIndex = (letterArrayIndex+1) % letterArray.length;
nback.numbers[index] = letter;
nback.numbers.innerHTML = letter;
nback.litCell = letter;
nback.current = letter;
nback.previous.push(nback.current);
};

Searching for a unique value across multiple parenthesis with RegEx on JavaScript?

Example
var value = "foo bar (foo(bar)(foo(bar)))";
And the value you want is
(foo(bar)(foo(bar)))
And not
(foo(bar)
As elclarns notes, JS doesn't have recursive regex, but regex is not the only tool, parenthesis counter should work, well
var x = "foo bar (foo(bar)(foo(bar))) foo bar";
var result = "";
var cnt = 0;
var record = false;
for(var i=0; i<x.length; ++i) {
var ch = x.charAt(i);
if(ch=="(") { ++cnt; record = true; }
if(ch==")") --cnt;
if(record) result+= ch;
if(record && !cnt) break;
}
if(cnt>0) record = ""; // parenthesis not enclosed
console.log(result); // (foo(bar)(foo(bar)))
This of course captures only the first parenthesis, but you can record them all in array and choose the longest result. This should be easy.
this should work.
var re = /\(.*\)/
var result = re.exec(value) //["(foo(bar)"]
It then will catch the biggest string between parenthesis.

Categories

Resources