As title. I tried the following javascript.
This will console.log() the same random number 20 times, but how do I go about 20 random characters? Are we using callback function?
var letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var insert = letters.charAt(Math.floor(Math.random() * letters.length));
var str = "0";
for (i = 0; i < 20; i++) {
setTimeout(function() {
var newStr = str.replace(/./, insert);
console.log(newStr)
}, 50 * i)
}
This line:
var insert = letters.charAt( Math.floor(Math.random()*letters.length) );
runs once and once only. It does not re-run the random part every time you ask for the value of insert.
You could rerun it manually every loop:
var letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var str = "0";
for(i=0; i<20; i++) {
setTimeout(function(){
var insert = letters.charAt( Math.floor(Math.random()*letters.length) );
var newStr = str.replace(/./, insert);
console.log(newStr)
}, 50*i)
}
But keep in mind that you might get the same character more than once, as by definition it is (pseudo) random - and therefore could pick the same character as has been previously picked.
To ensure you get a distinct random character each time you would have to remove a picked character from the list. Easier to do by converting the characters to an array and using splice to remove it once selected:
var letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split("");
var str = "0";
for(i=0; i<20; i++) {
setTimeout(function(){
var insert = Math.floor(Math.random()*letters.length);
var newStr = str.replace(/./, letters[insert]);
console.log(newStr)
letters.splice(insert,1);
}, 50*i)
}
I'm trying to write a function that will find an instance of text within a div and console.log all text that is after the '-' character. After the '-' character there are sometimes spaces and tabs, so I want to remove these up until the first text character. Here's what I have so far (that is not working at all):
var countryData = $(".countries-title").next().text();
//var regex = /(?<= - ).*/g;
let stringArray = countryData.replace(/\t/g, '').split('\r\n');
console.log(stringArray);
Any help is appreciated. Thanks
console.log('here is a - whole bunch of text'.match(/-\s*(.*)$/)[1]) will log out "whole bunch of text". Is that along the lines of what you are looking for? Let me know if you want me to elaborate.
Assuming you want to maintain all hyphens and formatting after the first hyphen and subsequent spaces you could use:
let textAfterHyphen = countryData.replace(/\s*-\s*/, '');
I am not sure if I understood all but here you have my solution:
$(document).ready(function returnString() {
$("#click-target").on("click",function(){
var newString = [];
var resultString = [];
var onlyChar =$(".target").text();
newString = onlyChar.split("");
for(var i = 0; i < newString.length; i++){
if(newString[i] == "-"){
resultString = newString.slice(i+1,newString.length).join("");
}
}
var k = 0;
for(var j = 0; j < resultString.length; j++){
if(resultString.charCodeAt(j) > 64 && resultString.charCodeAt(j) < 91){
k += j;
}
}
console.log(resultString.slice(k,resultString.length));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="target">Text- *^^^***Text to display</div>
<button id ="click-target">Click</button>
I am trying to use Javascript to split some data out of a url The url looks along the lines of....
var1=green&var2=yellow&newUrl=[url.php?id=2]
I am managing to split the url by the '&' signs to give me one array of three items. I am then trying to split this array by the first '=' sign to give me a list of fields and variables. Its working fine until it hits the second = sign within the newUrl field. Any ideas of how I can split this string at the first '=' sign.
my code so far is...
var href = $(this).attr("href");
var vars = href.split("&");
for(i=0; i < vars.length; ++i){
var str = vars[i].split("=");
alert(str[0] +':' +str[1]);
}
}
my results are
var1:green var2:yellow var3:[url.php?id
Any ideas?
**Edit to show my final code based on Wand Maker's solution **
var vars = href.split("&");
for(i=0; i < vars.length; ++i){
index = vars[i].indexOf("=")
var str = [ vars[i].substring(0, index), vars[i].substring(index)]
alert(str[0] +':' +str[1].substring(1);
}
Try something like below for splitting around =
index = vars[i].indexOf("=")
var str = [ vars[i].substring(0, index), vars[i].substring(index)]
You could use join() for the third element in the array as below:
var lst = href.split("&");
var var1 = href[0].split("=")[1];
var var2 = href[1].split("=")[1];
var var3 = href[2].split("=").slice(1,2).join("");
function splitFirstInstance(str,item){
var res = [];
var found = true;
res.push("");
for (var i = 0; i < str.length;i++){
if (str[i] === item && found === true){
res.push("");
found = false;
} else {
res[res.length-1] += str[i];
}
}
return res;
}
splitstr("I Want to Split First a","a"); // ["I W","nt to Split First a"]
Lets consider i have a string & want to extract uncommon keywords for SEO. $text = "This is some text. This is some text. Vending Machines are great.";
& Will define a array of common words to ignore keywords in extracted list like $commonWords = ['i','a','about','an','and','are','as','at','be','by','com','de','en','for','from','how','in','is','it','la','of','on','or','that','the','this','to','was','what','when','where','who','will','with','und','the','www'];
Expected output: Result=[some,text,machines,vending]
Would really appreciate if Could any one help us to write generic logic or procedure for the extracting keywords from string?
This can help ( it supports multi languages):
https://github.com/michaeldelorenzo/keyword-extractor
var sentence = "President Obama woke up Monday facing a Congressional defeat that many in both parties believed could hobble his presidency."
// Extract the keywords
var extraction_result = keyword_extractor.extract(sentence,{
language:"english",
remove_digits: true,
return_changed_case:true,
remove_duplicates: false
});
Some like this
var $commonWords = ['i','a','about','an','and','are','as','at','be','by','com','de','en','for','from','how','in','is','it','la','of','on','or','that','the','this','to','was','what','when','where','who','will','with','und','the','www'];
var $text = "This is some text. This is some text. Vending Machines are great.";
// Convert to lowercase
$text = $text.toLowerCase();
// replace unnesessary chars. leave only chars, numbers and space
$text = $text.replace(/[^\w\d ]/g, '');
var result = $text.split(' ');
// remove $commonWords
result = result.filter(function (word) {
return $commonWords.indexOf(word) === -1;
});
// Unique words
result = result.unique();
console.log(result);
var string = "This is some text. This is some text. Vending Machines are great.";
var substrings = ['your','words', 'here'],
var results = array();
for (var i = substrings.length - 1; i >= 0; --i) {
if (string.indexOf(substrings[i]) != -1) {
// str contains substrings[i]
array.push(substrings[i]);
}
}
var arrayLength = commonWords.length;
var words = []; //new array to say the words
for (var i = 0; i < arrayLength; i++) {
if ($text.indexOf(commonWords[i]) > -1){
words.push(commonWords[i]);
}
}
I wrote a simple program to analyze a string to find the word with the greatest amount of duplicate letters within it. It essentially takes a given string, breaks it up into an array of separated words, and then breaks up each separate word into alphabetically sorted groups of individual letters (which are then compared as prev and next, 2 at a time, as the containing array is iterated through). Any two adjacent and matching values found adds one tally to the hash-file next to the word in question, and the word with the most tallied pairs of duplicate letters is returned at the end as greatest. No matching pairs found in any word returns -1. This is what it's supposed to do.
Below, I've run into a problem: If I don't use a REGEXP to replace one of my matched characters, then my code gives false positives as it will count triplicates (eg, "EEE"), as two separate pairs, (eg, "EEE" = "EE & EE", instead of being viewed as "EE, E"). However, if I DO use the REGEXP below to prevent triplicate counts, then doing so breaks my loop mid-stride, and skips to the next word. Is there no way to make this way work? If not, would it be better to employ a REGEXP which deletes all chars EXCEPT the duplicate characters in question, and then perhaps I could divide the .length of each word by 2 to get the number of pairs remaining? Any ideas as to how to solve this would greatly help.
var str = "Helloo aplpplpp pie";
//var str = "no repting letrs";
//var str = "ceoderbyte";
function LetterCountI(str) {
var input = str.split(" ");
console.log(input);
console.log("\n")
var hashObject = {};
var word = "";
var count = 0;
for(var i = 0; i<input.length; i++) {
var currentItem = input[i];
var currentWordIntoChars = currentItem.split("").sort();
console.log(currentWordIntoChars);
var counter = 0;
for(var j=1; j<currentWordIntoChars.length; j++) {
console.log(currentWordIntoChars[j-1] + "=currentChar j-1");
console.log(currentWordIntoChars[j] + "=prev j");
console.log("-");
var final = currentItem;
if(currentWordIntoChars[j-1] == currentWordIntoChars[j]) {
counter++;
hashObject[final] = counter;
//currentWordIntoChars = currentWordIntoChars[j-1].replace(/[a-z]/gi, String.fromCharCode(currentItem.charCodeAt(0)+1));
//HERE REPLACE j-1 with random# or something
//to avoid 3 in a row being counted as 2 pair
//OR use regexp to remove all but pairs, and
//then divide .length/2 to get pairs.
console.log(counter + " === # total char pairs");
}
if(count<hashObject[currentItem]) {
word = final;
count = hashObject[currentItem];
}
}
}
console.log(hashObject);
console.log("\n");
for (var o in hashObject) if (o) return word;
return -1;
}
console.log(LetterCountI(str));
An other way to do it, consists to replace duplicate characters in a sorted word:
var str = "Helloo aplpplpp pie";
function LetterCountI(str) {
var input = str.split(" ");
var count = 0;
var result = -1;
for(var i = 0; i<input.length; i++) {
var nb = 0;
var sortedItem = input[i].split("").sort().join("");
sortedItem.replace(/(.)\1/g, function (_) { nb++ });
if (nb > count) {
count = nb;
result = input[i];
}
}
return result;
}
console.log(LetterCountI(str));
Notes: The replace method is only a way to increment nb using a callback function. You can do the same using the match method and counting results.
if two words have the same number of duplicates, the first word will be returned by default. You can easily change this behaviour with the condition of the if statement.
Whenever you find a match within a word, increment j by 1 to skip comparing the next letter.
var str = "Helloo aplpplpp pie";
//var str = "no repting letrs";
//var str = "ceoderbyte";
function LetterCountI(str)
{
var input = str.split(" ");
console.log(input);
console.log("\n")
var hashObject = {};
var word = "";
var count = 0;
for(var i = 0; i<input.length; i++)
{
var currentItem = input[i];
var currentWordIntoChars = currentItem.split("").sort();
console.log(currentWordIntoChars);
var counter = 0;
for(var j=1; j<currentWordIntoChars.length; j++)
{
console.log(currentWordIntoChars[j-1] + "=currentChar j-1");
console.log(currentWordIntoChars[j] + "=prev j");
console.log("-");
var final = currentItem;
if(currentWordIntoChars[j-1] == currentWordIntoChars[j])
{
counter++;
hashObject[final] = counter;
j++; // ADD HERE
console.log(counter + " === # total char pairs");
}
if(count<hashObject[currentItem])
{
word = final;
count = hashObject[currentItem];
}
}
}
console.log(hashObject);
console.log("\n");
for (var o in hashObject) if (o) return word;
return -1;
}
console.log(LetterCountI(str));