Can you match words in a url using a RegEx array? - javascript

I'm trying to grab specific words from a URL using RegEx. I've included the words as an Array but I can't seem to match or filter any of the words in the array. I always get an error that 'filter' is not a function although i appear to be using it much the same as others have before.
function replaceInput() {
var leadUrl = document.URL;
var utm_sources = [/linkedin/, /smartbrief/, /email_paid/, /paid_social/];
var get_source = leadUrl.filter(value => utm_sources.test(value));
var setUtm = get_source;
document.getElementById("LeadSourceTitle").placeholder = setUtm;
}
<html>
<head>
<link rel="stylesheet" href="styles.css">
<script src="utm-url-test.js"></script>
</head>
<body>
<h1>Form test</h1>
<p>Populate the webform input with the utm of the url.</p>
<form>
<input id="LeadSourceTitle" placeholder="This should be replaced with UTM" onfocus="replaceInput()"></input>
</form>
</body>
</html>
Ideally what I want to do is check to see whether these words exist, then add a value to a form input with the corresponding value.
Thanks

If I read your code correct, you are looking for the path of an url, not the url itself. The path can be found in location.pathname. Using RegExp.match delivers null if nothing is matched, and an array (you filter if necessary) if a match is found.
So, do something along the lines of:
const re = /\/linkedin\/|\/smartbrief\/|\/email_paid\/|\/paid_social\//i;
const path = location.pathname.match(re);
const pathFaked1 = "/linkedin/?foo=bar&email_paid=1".match(re);
const pathFaked2 = "/email_paid/nope/shouldpaynow".match(re);
console.log(path);
console.log(pathFaked1.join(", "));
console.log(pathFaked2.join(", "));

Related

Can't get child field font in pdf-lib.js

I am trying to get a list of fields and which fonts are assigned to them. I can use form.getFields() to get a list of fields in the form. I can then run through the "dict" to find the font name - Easy!
Ex1
However, when I am working with a field that has "Child Fields", for example, a pdf with text fields of the same name, it does not have this font parameter.
It only has "/Kids" which contains some sort of reference I haven't been able to understand
Ex2
I have also tried this:
createPDFAcroFields(fields\[1\].acroField.Kids())
However, it returns a blank array. Any help would be greatly appreciated.
Here's a jsFidle that grabs the fields and can show you the objects that are missing the font in the console!
https://jsfiddle.net/xek1stmz/13/
<html>
<head>
<meta charset="utf-8" />
<script src="https://unpkg.com/pdf-lib/dist/pdf-lib.min.js"></script>
</head>
<script>
const { PDFDocument } = PDFLib
async function getFieldFonts() {
// Fetch the PDF with form fields
const formUrl = 'https://partners.metas.global/Code39.pdf'
const formPdfBytes = await fetch(formUrl).then(res => res.arrayBuffer())
// Load a PDF with form fields
const pdfDoc = await PDFDocument.load(formPdfBytes)
// Get the form containing all the fields
form = pdfDoc.getForm();
fields = form.getFields();
console.log(fields);
}
getFieldFonts();
</script>
</html>

How can I use a parameter to change HTML text?

I'm using an API, and am trying to access the value of product.shoeName to change text on my HTML page. This is my code:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript"
src="shoepoo.js">
</script>
</head>
<body>
<div>
<p id="text" style="color:purple;
font-weight:bold;font-size:20px;">
</p>
<script type="text/javascript"> shoeName(); </script>
</div>
</body>
</html>
const SneaksAPI = require('sneaks-api');
const sneaks = new SneaksAPI();
//getProducts(keyword, limit, callback) takes in a keyword and limit and returns a product array
function shoeName(){
sneaks.getProducts("Jumbo Blazer", 1, function(err, products){
products.forEach(
function names (product) {
document.getElementById("text").innerHTML = product.shoeName;
})
});
};
Basically, I want product.shoeName to be shown as text, but nothing is showing up. How can I fix this? I understand it's a local function which is probably stopping the data from being shown (or something like that), but how can I work around this?
Made below changes in shoepoo.js
products.forEach((product)=> {
document.getElementById("text").innerHTML = product.shoeName;
});
But you need to create dynamic HTML components if there is multiple data in products. Otherwise, it set the last shoeName in the paragraph component.

Issue with API url: cannot seem to pass parameters correctly

I'm new at APIs and am trying for the first time to create a gallery using Flickr API, but I'm really struggling getting it to work properly.
I have created the url correctly, and if I insert the search parameters directly in the url, when I console log I can see the correct list of images. The issue occurs when I'm trying to pass parameters from variables into the url. And the error manifests in two different ways, depending whether I put the url variable before or after the parameters variables.
Case 1:
var url = `https://www.flickr.com/services/rest/?method=flickr.photos.search&api_key=XXXXXXXXXXXXXX&text=${searchWord}&per_page=${perPage}&page=${page}&format=json&nojsoncallback=1`;
var searchWord = document.getElementById('input').value;
var perPage = 50;
var page = 1;
In this case it will console log data, but using parameters of its choice.
Case 2:
var searchWord = document.getElementById('input').value;
var perPage = 50;
var page = 1;
var url = `https://www.flickr.com/services/rest/?method=flickr.photos.search&api_key=XXXXXXXXXXXXXX&text=${searchWord}&per_page=${perPage}&page=${page}&format=json&nojsoncallback=1`;
In this case it will return the following error message: {stat: "fail", code: 3, message: "Parameterless searches have been disabled. Please use flickr.photos.getRecent instead."}
I seem to not be passing parameters to the url correctly, cause I'm also having an issue when trying to create the gallery itself, where when I'm trying to pass the necessary ids from the images in the API array to the image url I'm creating, these parameters end up being undefined.
This is the code I've written:
function createGallery(photos) {
for (let photo of Object.keys(photos)) {
const imgElem = document.createElement('li');
imgElem.innerHTML = `<img src='https://farm{${photo.farm}}.staticflickr.com/{${photo.server}}/{${photo.id}}_{${photo.secret}}_[mstzb].jpg'></img>`;
imgElem.setAttribute('img-id', photo.id);
gallery.append(imgElem);
}
}
Just for an overview, here is the last bit of my JS:
//Fetch API
async function start() {
const response = await fetch (url)
const data = await response.json()
console.log(data)
createGallery(data)
}
//Call functions
search()
And here is my HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<main>
<input type="text" id="input">
<button id="search">Go</button>
<ul id="gallery"></ul>
</main>
<script src="script.js"></script>
</body>
</html>
Anyone can explain what I'm doing wrong?? Thanks so much in advance :)
EDIT: I tried appending the variables using pluses instead of using template literals, like so:
var url = 'https://www.flickr.com/services/rest/?method=flickr.photos.search&api_key=XXXXXXXXXXXXXX&text='+searchWord+'&per_page='+perPage+'&page='+page+'&format=json&nojsoncallback=1';
But both ways give exactly the same result.
You are basically appending the parameters incorrectly.
You have the following:
var perPage = 50;
var page = 1;
var url = `https://www.flickr.com/services/rest/?method=flickr.photos.search&api_key=XXXXXXXXXXXXXX&text=${searchWord}&per_page=${perPage}&page=${page}&format=json&nojsoncallback=1`;
When you define that url it should be similar to this ..
var url = `https://www.flickr.com/services/rest/?method=flickr.photos.search&api_key=XXXXXXXXXXXXXX&text=' + searchWord + '&per_page=' + perPage + '&page=' + page + '&format=json&nojsoncallback=1'
Please note the difference there, we are actually just building up the url var by appending the JS variables to the String. There is no ${} access to the declared page and perPage JS vars...

Scrape html with js

I'm trying to get the html of www.soccerway.com. In particular this:
that have the label-wrapper class I also tried with: select.nav-select but I can't get any content. What I did is:
1) Created a php filed called grabber.php, this file have this code:
<?php echo file_get_contents($_GET['url']); ?>
2) Created a index.html file with this content:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta charset=utf-8 />
<title>test</title>
</head>
<body>
<div id="response"></div>
</body>
<script>
$(function(){
var contentURI= 'http://soccerway.com';
$('#response').load('grabber.php?url='+ encodeURIComponent(contentURI) + ' #label-wrapper');
});
var LI = document.querySelectorAll(".list li");
var result = {};
for(var i=0; i<LI.length; i++){
var el = LI[i];
var elData = el.dataset.value;
if(elData) result[el.innerHTML] = elData; // Only if element has data-value attr
}
console.log( result );
</script>
</html>
in the div there is no content grabbed, I tested my js code for get all the link and working but I've inserted the html page manually.
I see a couple issues here.
var contentURI= 'http:/soccerway.com #label-wrapper';
You're missing the second slash in http://, and you're passing a URL with a space and an ID to file_get_contents. You'll want this instead:
var contentURI = 'http://soccerway.com/';
and then you'll need to parse out the item you're interested in from the resulting HTML.
The #label-wrapper needs to be in the jQuery load() call, not the file_get_contents, and the contentURI variable needs to be properly escaped with encodeURIComponent:
$('#response').load('grabber.php?url='+ encodeURIComponent(contentURI) + ' #label-wrapper');
Your code also contains a massive vulnerability that's potentially very dangerous, as it allows anyone to access grabber.php with a url value that's a file location on your server. This could compromise your database password or other sensitive data on the server.

Generate dynamic hyperlink based on querystring

I wanna generate Hyperlink based on query string .Let me explain it more
Topics clicked rite now:(here I want my hyperlinks)....,....
1.Cat1
2.Cat2
3.Cat3
when i click cat1 it generate querystring: ?Cat=Cat1
when I click on cat2 it will generate querystring ?Cat=Cat2
so based on that I want to create hyperlink whose
text is query string(value)
and url is url-(name and value of that query string)lets say for cat1
if currently url is http://www.google.com/?Cat=Cat1&subcat=subcat1
so text should be cat1(and its url should be www.google.com/?subcat=subcat1)
You may want to take a look at the jquery.query plugin. In particular the get function which returns an array of tokens that you can iterate over.
Something like this should get you started:
<html>
<head>
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.js"></script>
<script type="text/javascript" src="jquery.query.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.each($.query.get(), function(val, prop) {
$('.menu').append($('<a />').attr('href', $.query.empty().set(val, prop).toString()).text(val));
$('.menu').append($('<br />'));
});
});
</script>
</head>
<body>
<div class="menu">
</div>
</body>
</html>
i would say that probably the way to go for this is the following (syntax isnt correct most likely)
I believe this is some regular string manipulation..
var cat1 = "topic1";
var cat2 = "topic2";
var subcat1 = "subtopic1"; etc
url = "http://google.com/?cat=" + cat1 + "&subcat=" + subcat1
<a href=url/>CAT 1 Link<a>
i hope this helps

Categories