Implementing wildcard at end of a string - javascript

I looked through a number of posts (and other websites) and I seem to have a hit a roadblock. I have the following array:
var data_dictionary = ["youtube.com", "facebook.com", "youtube.com/feed/subscriptions", "twitter.com"]
I'm trying to return data for everything that has youtube.com*. Below is the relevant snippet of my function:
var result = []
for (var i=0; i<data_dictionary.length; i++) {
if (data_dictionary[i].page == /^youtube.com/) {
result.push (data_dictionary[i].page,data_dictionary[i].share)
}
}
break;
}
return result
The problematic area is in the if clause (/^youtube.com/). How can I receive the following return:
["youtube.com" , "youtube.com/feed/subscriptions"]

You can use Array.prototype.filter() method to filter array and RegExp.prototype.test() to check for match.
var data_dictionary = ["youtube.com", "facebook.com", "youtube.com/feed/subscriptions", "twitter.com"];
function check(data_dictionary) {
return data_dictionary.filter(function(v) {
return /^youtube\.com/.test(v);
// using indexOf
// v.indexOf('youtube.com') == 0;
});
}
console.log(check(data_dictionary));
FYI: Your if condition will be only true if the string is '/^youtube.com/'. ie, ('/^youtube.com/' == /^youtube.com/) === true. Your code will work if you changed the if condition to /^youtube.com/.test(data_dictionary[i]). Also in the provided data page and share properties are undefined only plain strings are the element.

Using the same approach that you had before. However using ".filter" won't be a bad idea, but I will suggest you compare their benchmark
var data_dictionary = ["youtube.com", "facebook.com", "youtube.com/feed/subscriptions", "twitter.com"];
var pattern = /^youtube.com/;
var result = [];
var i = 0;
function loop (args) {
for (i; i < args.length; i++) {
if (pattern.test(args[i])) {
result.push(args[i]);
}
}
return result;
}
console.log(loop(data_dictionary)) // ["youtube.com" , "youtube.com/feed/subscriptions"]
Comparing the speed below I would suggest you use the approach above

No need for regex here you can do like this;
var data_dictionary = ["youtube.com", "facebook.com", "youtube.com/feed/subscriptions", "twitter.com"],
filtered = data_dictionary.filter(e => !!~e.indexOf("youtube.com") && e);
document.write("<pre>" + JSON.stringify(filtered) + "</pre>");
Or if you want a faster solution still with Array methods then
var data_dictionary = ["youtube.com", "facebook.com", "youtube.com/feed/subscriptions", "twitter.com"],
filtered = data_dictionary.reduce((p,c) => !!~c.indexOf("youtube.com") ? p.concat(c):p,[]);
document.write("<pre>" + JSON.stringify(filtered) + "</pre>");

Related

Why is this for loop reverting to 0 and never getting to the end of the size of this array

This problem refers to the hackerank anagram question here:
For some reason, this for loop never completes. It gets to 3 (-2 from the length of the array it is iterating over) and then goes back to 0 and I can't tell why.
const dictionary = ['hack', 'a' , 'rank' , 'khac','ackh']
const query = ['a','nark','bs','hack','stair']
console.log(stringAnagram(dictionary, query))
function stringAnagram(dictionary, query){
let sortedDictionary=[];
let sortedQuery = [];
let alphabetisedWord;
let sortedWord;
let anagramsCount = [];
// sort them
for(let i = 0; i<dictionary.length-1; i++){
sortedWord= dictionary[i];
if(dictionary[i].length > 1){
sortedWord= sortedWord.split('');
console.log('sortedWord: ',sortedWord)
sortedWord= sortedWord.sort();
console.log('sortedWord: ',sortedWord)
sortedWord= sortedWord.join('');
console.log('sortedWord: ',sortedWord)
sortedDictionary[i] = sortedWord;
} else {
sortedDictionary[i] = sortedWord;
}
console.log(i, dictionary.length)
}
for(let i = 0; i<query.length-1; i++){
alphabetisedWord = query[i];
if(query[i].length > 1){
alphabetisedWord = alphabetisedWord.split('');
console.log('alpha : ', alphabetisedWord)
alphabetisedWord = alphabetisedWord.sort();
alphabetisedWord = alphabetisedWord.join('');
}
var regex = new RegExp("/" + alphabetisedWord + "/", "g");
console.log(stringAnagram(dictionary, query))
anagramsCount[i] = sortedDictionary.toString().match(regex).length
sortedQuery[i] = alphabetisedWord;
}
return anagramsCount;
}
Can anyone tell what's causing this? I have tried logging all the indexes and words but I did a similar question earlier with a similar method of answering - only this time, the endless loop has appeared and I have never seen this before.
If a simple problem seems impossible, you're doing it a wrong way... eek talking to myself too
const dictionary = ['hack', 'a' , 'rank' , 'khac','ackh']
const query = ['a','nark','bs','hack','stair']
console.log(stringAnagram(dictionary, query))
function stringAnagram(dd,qq){
var j=(x)=>{return JSON.parse(JSON.stringify(x))} //function to ensure an object isn't passed as pointer JUST IN CASE and to that dude critisizing this part, stringifying an already correctly evaluated obj works(therefore parsing that would be parsing a correctly stringified obj)
var d=j(dd); var q=j(qq)
//make words in both query and dictionary now have their words in only 1 format(so that indexOf would work like a charm)
d=d.map(a=>{return a.split``.sort().join``})
q=q.map(a=>{return a.split``.sort().join``})
//now onto indexOf logic(returns the FIRST find of what ur looking for in an array)
var arr=[]
q.forEach(a=>{
var i=0
while(d.indexOf(a)!=-1){
var y=d.indexOf(a)
i++;d.splice(y,1)
}
arr.push(i)
})
return(arr)
}

When parsing XML with recursive function, how do I return a string or array from that function?

I've got a working recursive function which goes through an XML doc looking for a matching node name, and then logging matching values...I'm trying to modify it to return a string or an array, and can't figure it out.
This is in Google Apps script. I've tried passing in a blank string into the function, and then returning it at the end, but it doesn't work. Here is the working Logger function:
function logChildren(elements, dataRequired){
for (var i = 0; i < elements.length; i++) {
if (elements[i].getName() == dataRequired){
Logger.log(elements[i].getText());
}
if(elements[i].getContentSize() > 1){
var children = elements[i].getChildren();
logChildren(children, dataRequired);
}
}
};
I tried passing in an empty string, and then returning it like this but it doesn't work:
function logChildren(elements, dataRequired, str){
for (var i = 0; i < elements.length; i++) {
if (elements[i].getName() == dataRequired){
str = str + ", " + elements[i].getText();
}
if(elements[i].getContentSize() > 1){
var children = elements[i].getChildren();
logChildren(children, dataRequired, str);
}
}
return str
};
How do I get a string or array OUT of this function, rather than just console logging it?
Instead of returning str try without it, because str will have all the values. If you return str it might collapse the current iteration. Please let us know whether this worked
Providing your elements is already parsed and valid, this should work.
function logChildren(elements, dataRequired){
values = [];
req = elements.getElementsByTagName(dataRequired);
for (var i = 0; i < req.length; i++) {
values.push(req[i].childNodes[0].nodeValue);
}
return values
};
elements = "<house>" +
"<name>hello</name>" +
"<town>world</town>" +
"<name>cat</name>" +
"<folder>" +
"<name>kitty</name>" +
"</folder>" +
"</house>";
p = new DOMParser();
elements = p.parseFromString(elements, "text/xml");
newValues = logChildren(elements, "name")
console.log(newValues);
I've included my own little xml just to test, and it returns an array.
As you can see, getElementsByTagName even returns values in sub folders.
You should use a global variable or another function, so that the output variable str is outside the scope of the recursed function.
var str = "";//holds all data of recursion
function logChildren(elements, dataRequired){
..
str += ", " + elements[i].getText();
..
}

Converting a badly stringfied json to a json object

I have some data i am pulling from a web service. This is the string
(Body:'3886' MessageProperties [headers={}, timestamp=null,
messageId=null, userId=null, receivedUserId=null, appId=null,
clusterId=null, type=null, correlationId=null,
correlationIdString=null, replyTo=null,
contentType=application/x-java-serialized-object,
contentEncoding=null, contentLength=0, deliveryMode=null,
receivedDeliveryMode=PERSISTENT, expiration=null, priority=0,
redelivered=false, receivedExchange=,
receivedRoutingKey=bottomlesspit, receivedDelay=null, deliveryTag=62,
messageCount=0, consumerTag=amq.ctag-sCwfLaMEqWp2GkFwFrY1yg,
consumerQueue=bottomlesspit])
It looks like json but the key value pairs are almost fine but the most important key which is Body isn't like other keys as the string would tell.
I need to read the value of Body and be able to get the value like this
console.log(d.body);
//This above outputs the string as shown
obj = eval('{' + d.body + '}');
console.log(obj);
var match = "Body";
var val = obj.find( function(item) { return item.key == match } );
console.log(val);
How can i read the value of the key Body?.
Use this regular expression instead of a match Body:
\bBody:'(\d*)'
This will catch the Body number in group 1.
You can write a parser function get string and extract values. A very simple function is here. You can modify it also for all exceptions exist.
var str = `(Body:'3886' MessageProperties [headers={}, timestamp=null, messageId=null, userId=null, receivedUserId=null, appId=null, clusterId=null, type=null, correlationId=null, correlationIdString=null, replyTo=null, contentType=application/x-java-serialized-object, contentEncoding=null, contentLength=0, deliveryMode=null, receivedDeliveryMode=PERSISTENT, expiration=null, priority=0, redelivered=false, receivedExchange=, receivedRoutingKey=bottomlesspit, receivedDelay=null, deliveryTag=62, messageCount=0, consumerTag=amq.ctag-sCwfLaMEqWp2GkFwFrY1yg, consumerQueue=bottomlesspit])`;
function f(inp) {
var index = str.indexOf(inp),
endIndex;
for(var i = index; i < str.length; i ++) {
if(str[i] == ',') {
endIndex = i;
break;
}
}
var output = str.substr(index, endIndex).split('=');
return output;
}
console.log(f('consumerQueue'));
Why not use a regex to match and extract the Body.
Example:
const match = d.body.match(/Body:\'(.+)\'/)
if (match) {
const body = match[1] // This is the value of Body
} else {
// Unable to find Body, handle it here
}

How to remove function name from Javascript object

I have a Leaflet map and I want to edit a polygon. I successfully do this, but when I finish the editing, the coordinates are saved like:
,,LatLng(44.94633, 26.00773),LatLng(44.93588, 25.94318),LatLng(44.94245, 25.90645),LatLng(44.91814, 25.87074),LatLng(44.91328, 25.9346),LatLng(44.90015, 25.97031),LatLng(44.90112, 26.11519)"
I only want to have the coordinates without function name. How can I do this? Thanks!
map.on("dragend", function(e){
poligon = polygon.getLatLngs();
poligon1 = poligon.toString();
$('#geo').val(poligon1);
console.log(poligon1);
});
Dont use toString() u will get an array of objects
var arr=[];
console.log(polygon.getLatLngs());
for(var i=0;i<arr.length;i++){
arr=polygon.getLatLngs();
console.log(arr[i].lat);
console.log(arr[i].lng);
console.log("("+arr[i].lat +","+arr[i].lng+")");
}
Resolved it by writing one line:
poligon = polygon.getLatLngs();
//this is what I added
poligon2=poligon.join(',').match(/([\d\.]+)/g).join(',')
You can override toString method of LatLng prototype at your project init
L.LatLng.prototype.toString = function() {
return '(' + this.lat + ',' + this.lng + ')';
}
Then you'll see output like this cause Array.toString() recursively call toString() on every element in collection.
(44.94633, 26.00773),(44.94633, 26.00773)
I'll just add an answer.
This should work in general: give it a string, it will try to find all numbers, and return them in an array.
<script>
var mystring = "LatLng(44.94633, 26.00773),LatLng(44.93588, 25.94318),LatLng(44.94245, 25.90645),LatLng(44.91814, 25.87074),LatLng(44.91328, 25.9346),LatLng(44.90015, 25.97031),LatLng(44.90112, 26.11519)";
function isNumeric(input) {
return (input - 0) == input && input.length > 0;
}
// reads a string, finds numbers (float), returns the numbers in an array
function numbersInString(string) {
var s = 0, temp=0, result = [];
for(var i=0; i<string.length; i++) {
s = string.substr(i,1); // search 1 character, see if it's a number (digit)
if(isNumeric(s)) {
// parseFloat wil read as many characters as it can, and drop the rest
temp = parseFloat(string.substr(i));
// okay, now skip the length of the float
i = i + temp.toString().length ;
result.push(temp);
}
}
return result;
}
window.onload = function() {
var numbers = numbersInString(mystring);
document.getElementById('log').innerHTML += numbers.join(',');
}
</script>
<div id="log"></div>

Get string from url using jQuery?

Say I have http://www.mysite.com/index.php?=332
Is it possible to retrieve the string after ?= using jQuery? I've been looking around Google only to find a lot of Ajax and URL vars information which doesn't seem to give me any idea.
if (url.indexOf("?=") > 0) {
alert('do this');
}
window.location is your friend
Specifically window.location.search
First your query string is not correct, then you can simply take the substring between the indexOf '?=' + 1 and the length of the string. Please see : http://www.w3schools.com/jsref/jsref_substring.asp
When it is easy to do without JQuery, do it with js only.
here is a code snippet (not by me , don't remember the source) for returning a value from a query string by providing a name
$.urlParam = function(name){
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (!results)
{ return 0; }
return results[1] || 0;
}
var myArgs = window.location.search.slice(1)
var args = myArgs.split("&") // splits on the & if that's what you need
var params = {}
var temp = []
for (var i = 0; i < args.length; i++) {
temp = args[i].split("=")
params[temp[0]] = temp[1]
}
// var url = "http://abc.com?a=b&c=d"
// params now might look like this:
// {
// a: "a",
// c: "d"
// }
What are you trying to do? You very well may be doing it wrong if you're reading the URL.

Categories

Resources