I have a doc which is a message in microsoft graph db and i am trying to parse some token / tracking nbr from the body. So in my case i get the info and then i pass the body to my regex function. And there is my problem, when i use
const str = messages.value[0].body
console.log(str)
// check if we have a tracking id in the body
const trackingId = regex.getTrackingId(str)
if(trackingId){
console.log('We have a Tracking ID ' + trackingId)
}
it fails here is my getTrackingId function
function getTrackingId(body) {
try {
console.log(body)
const regex = /http:\/\/demo.example.com\/campaign\/(.+)\/tracker.png/gm;
while ((m = regex.exec(body)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
console.log(m)
if (m.length == 2) {
return m[1]
} else {
return null
}
}
} catch (error) {
console.log(error) }}
i made sure the text is past to the function and thats the case. if i take the body and make it static it works so realy not sure whats going on ?
const str = `{ contentType: 'html',
content:
'<html>\r\n<head>\r\n<meta http-equiv="Content-Type" content="text/html; charset=utf-8">\r\n<meta content="text/html; charset=us-ascii">\r\n</head>\r\n<body>\r\n<p>This is a Test Email which will be deleted</p>\r\n<img src="http://demo.example.com/campaign/xHMmLOSEpv/tracker.png">\r\n</body>\r\n</html>\r\n' }
"`;
function getTrackingId(body) {
try {
const regex = /http:\/\/demo.example.com\/campaign\/(.+)\/tracker.png/gm;
while ((m = regex.exec(body)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
if (m.length == 2) {
console.log('Tracking Nbr : ' + m[1])
} else {
console.log('No Tracking Nbr')
}
}
} catch (error) {
console.log(error)
}
}
getTrackingId(str)
After digging a little deeper i found the issue. My RegEx code is fine. The problem is that when i get the response from Microsoft API and assign it to the str variable it sees it as an object. Since Regex does not like that it never matches anything.
So the simple fix was to to
const str = JSON.stringify(messages.value[0].body)
i got to it when i tried to do a simple indexOf on str and got errors.
Related
so i have this
client.on("chat", async (channel, userstate, message, self) => {
console.log(`Received message: ${message} from user ${userstate.username}`);
if (self) return;
if (userstate.username === "funtoon") {
const catchRegex = /!catch (.*)/;
const match = message.match(catchRegex);
if (match && match[1]) {
const response = await axios.get(
"https://grynsoft.com/spos-app/?c=Vod_Kanakas&u=Vod_Kanakas"
);
const $ = cheerio.load(response.data);
const textRegex = new RegExp(
`<b style="color: yellow;">${match[1]}<\/b>`
);
const textMatch = $("html").html().match(textRegex);
if (textMatch) {
console.log("Both style and match[1] are present");
} else if (match[1]) {
console.log("Only match[1] present");
} else {
console.log("Neither was present");
}
}
}
});
expected results are
if match[1] and style are present in the same element do nothing
if only match[1] is present in the element Only match[1] present
if neither match[1] nor style are present 'Neither was present"
test results are
Both style and match[1] are present, doing nothing
Only match[1] present
Only match[1] present
i dont want to perform random releases if i dont have them to begin with. how do i make it so 3 works right without breaking the others?
tried using chatgpt but to fix this but nothing i gave me worked.
I'd changed the last if/elses statement to :
[...]
const textMatch = $('html').html().match(textRegex);
if (textMatch && textMatch[0].includes(`style="color: yellow;"`)) {
console.log("Both style and match[1] are present");
} else if (textMatch) {
console.log("Only match[1] present")
} else {
console.log("Neither was present")
}
[...]
});
Code contains errors: Uncaught SyntaxError: Unexpected token 'if' at undefined:18:22
When uploading to greasyfork I've got that error.
The javascript file is:
// ==UserScript==
// #name Docubuilder
// #namespace Editors
// #match *://*
// #grant none
// #version 1.0
// #author Josiah
// #description Josiah's Docubuilder builds anything on the current document. This also works on HTML files!
// ==/UserScript==
console.log("Starting to make builder's button so hang on!")
function buildermain() {
tobuild = prompt("Insert any valid HTML element, cancel or input nothing and a tab will open with a list of HTML elements.")
if (tobuild == '' || tobuild == null) {
window.open("https://developer.mozilla.org/en-US/docs/Web/HTML/Element")
} else {
mynew = document.createElement(tobuild)
myhtml = prompt("Text to display...")
mynew.innerHTML = if (!(myhtml == null)) { return myhtml } else { return 'A random ' + tobuild + '.'}
document.body.insertBefore(mynew, null)
alert("Done! Check the bottom of the page!")
}
}
const builderbutton = document.createElement('button')
builderbutton.onClick = "buildermain()"
builderbutton.innerHTML = "Start building some stuff!"
document.body.insertBefore(builderbutton, document.body.firstChild)
Maybe it was the if, so I'm trying to find a way to return a string to a variable in a single line.
Any help here?
Conditional (ternary) operator may help:mynew.innerHTML = (!(myhtml == null)) ? myhtml : 'A random ' + tobuild + '.';
The problem is that if() does not return a value. It will not assign a value to the property innerHTML.
There are some options to solve this.
Create a function
function buildermain() {
// [...]
mynew.innerHTML = getHtml(myhtml, tobuild);
// [...]
}
const getHtml = (myhtml, tobuild) => {
if (myhtml !== null) {
return myhtml;
}
return `A random ${tobuild}.`;
}
Use the ternary operator
function buildermain() {
// [...]
mynew.innerHTML = myhtml !== null ? myhtml : `A random ${tobuild}.`;
// [...]
}
Use if, else (correct) without direct assignemt to innerHtml
function buildermain() {
// [...]
if (myhtml !== null) {
mynew.innerHTML = myhtml;
} else {
mynew.innerHTML = `A random ${tobuild}.`;
}
// [...]
}
My url looks like this = https://studentscafe.com/menu/2
I'm trying to check whether or not it has 2 different url params...
1.) ?dinner=1
or
2.) &dinner=1
If #1 is present, do nothing
If #2 is present, do nothing
But if neither are present, default to adding ?dinner=1 to the url.
Is there a better way to have a default do nothing in an if statement? Fiddle here for example.
var path = 'https://studentscafe.com/menu/2';
if (path.indexOf('?dinner=1') >= 1) {
console.log('has ?');
// do nothing leave url as it is
} else {
console.log('does not have ?');
if (path.indexOf('&dinner=1') >= 1) {
// do nothing leave url as it is
} else {
path = path + '?dinner=1';
}
}
Expected output: if the url doesn't have #1 or #2: https://studentscafe.com/menu/2?dinner=1
Instead of
if (something) {
// do nothing
} else {
// do what you need
}
You can use
if (!something) {
// do what you need
}
In your case:
if (path.indexOf('?dinner=1') == -1 && path.indexOf('&dinner=1') == -1) {
path = path + '?dinner=1';
}
Using a regular expression and the ! negation operator, this can be rather simple:
var path = 'https://studentscafe.com/menu/2';
if (!/[?&]dinner=1/.test(path)) {
path += '?dinner=1';
}
console.log(path);
You can do this way.
var path = 'https://studentscafe.com/menu/2';
// Since there is no change to path if it contains either ?dinner=1 or &dinner=1
if (path.indexOf('dinner=1') >= 1) {
console.log('has dinner');
// do nothing leave url as it is
} else {
path = path + '?dinner=1';
}
In modern JS you may simply do like
['?dinner=1','?dinner=2'].every(s => !path.includes(s)) && (path += '?dinner=1');
please can you tell me what does location.hash.match return if there is no hash ?
My code :
function getHashValue(key) {
return location.hash.match(new RegExp(key + '=([^&]*)'))[1];
}
test = getHashValue('test');
if (test == 'abc') {
//code WORKS
}
else if (test == 'sal') {
//code WORKS
}
else if (test == "") {
//code DOESNT WORKS
}
but It doesn't works
I forget to mentionned that my code 'getHashValue' return the value of the hash Exemple : #test=abc
sorry I forget to mentionned it
Why not just?
test = getHashValue('test');
if (test === undefined) {
//code
}
EDIT
The error was from a null return in the match() call. The following change will return an empty string if the match is "" or null.
function getHashValue(key) {
var match = location.hash .match(new RegExp(key + '=([^&]*)'));
return match ? match[1] : "";
}
If you run location.hash in your browser console on any website where you're not using a hash, you'll find that it returns the empty string "".
As such, a regex match on that will find 0 results, returning null, at which point, you try to access null[1]...
location.hash will be empty string and your function:
function getHashValue(key) {
return location.hash.match(new RegExp(key + '=([^&]*)'))[1];
}
Will indeed return undefined. The problem is that you are checking "undefined" value incorrectly. Change your code to:
test = getHashValue('test');
if (typeof(test) === 'undefined') {
//code
}
I'm getting a frustrating javascript error in IE7 that I can't get around. It is working fine in Chrome and Firefox, but not in IE..
The line I am getting the error in is: item = listGetAt(list,'1','-');
This is calling the following custom method:
function listGetAt(list,position,delimiter) {
if(delimiter == null) { delimiter = '-'; }
list = list.split(delimiter);
if(list.length > position) {
return list[position];
} else {
return list.length;
}
}
Can anyone see something I can't?
Many thanks in advance for any help.
Jason
Poor code
Why pass a string as a numeric parameter?
I would consider
function listGetAt(list,position,delimiter) {
delimiter = delimiter || '-';
if (list.indexOf(delimiter) ==-1) return -1;
list = list.split(delimiter);
return list.length>=position?list[position]:null;
}