How do I make the quotations in this script clickable link? - javascript

I have this script from codelifter and it works great.
I would like that if the quotations below contained a url then it would become clickable.
Any help would be great.
Thanks
<script language="JavaScript">
// ==============================================
// Copyright 2004 by CodeLifter.com
// Free for all; but please leave in this header.
// ==============================================
var Quotation=new Array() // do not change this!
// Set up the quotations to be shown, below.
// To add more quotations, continue with the
// pattern, adding to the array. Remember
// to increment the Quotation[x] index!
Quotation[0] = "http://www.youtube.com/watch?v=zH6U5y086hw";
Quotation[1] = "Sanity is a golden apple with no shoelaces.";
Quotation[2] = "Repent! The end is coming, $9.95 at Amazon.";
Quotation[3] = "Honesty blurts where deception sneezes.";
Quotation[4] = "Pastry satisfies where art is unavailable.";
Quotation[5] = "Delete not, lest you, too, be deleted.";
Quotation[6] = "O! Youth! What a pain in the backside.";
Quotation[7] = "Wishes are like goldfish with propellors.";
Quotation[8] = "Love the river's \"beauty\", but live on a hill.";
Quotation[9] = "Invention is the mother of too many useless toys.";
// ======================================
// Do not change anything below this line
// ======================================
var Q = Quotation.length;
var whichQuotation=Math.round(Math.random()*(Q-1));
function showQuotation(){document.write(Quotation[whichQuotation]);}
showQuotation();
</script>

This is what I would do:
Assume quotation begins with http(s)://
In ShowQuotation: Use a regexp to identify such strings. Might be unnecessarily complicated. Check if a length-7 substring is http:// OR length-8 substring is https:// , assume the rest is all part of the URL
Make it a link

function showQuotation(){
if(Quotation[whichQuotation].substr(0,7)=='http://' || Quotation[whichQuotation].substr(0,8)=='https://')
document.write(''+Quotation[whichQuotation]+'');
else
document.write(Quotation[whichQuotation]);
}

Related

Playing a Sound Notification when Specific Text on Page Appears

I'm trying to figure out a way to play a sound notification whenever the phrase "2 credits" appears in the top right corner on a specific website at: https://www.submithub.com/. As it stands, that specific area of the site oscillates between "0 credits" and "2 credits" depending on if you've submitted to the site within the last few hours. Once you are able to submit again, the text changes to "2 credits."
I have also provided a screenshot of what I am talking about:
I have been using code primarily derived from the following StackOverflow thread: How can I have a Tampermonkey userscript play a sound when a specific word appears on a page?
Here is the code that I am working with:
// ==UserScript==
// #name SubmitHub Notification
// #include https://www.submithub.com/
// #grant none
// ==/UserScript==
/* eslint-disable no-multi-spaces */
//-- Set the watched terms using the awesome power of regex.
var watchRegx = /\b2 credits\b/i;
var alrtSound = new Audio ("data:audio/mp3;base64,SUQzAwAAAAAAIVRYWFgAAAAXAAAARW5jb2RlZCBieQBMYXZmNTIuMTYuMP/7kGQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEluZm8AAAAPAAAACAAADrAAICAgICAgICAgICAgQEBAQEBAQEBAQEBAYGBgYGBgYGBgYGBgYICAgICAgICAgICAgKCgoKCgoKCgoKCgoKDAwMDAwMDAwMDAwMDg4ODg4ODg4ODg4ODg////////////////AAAAOUxBTUUzLjk5cgGqAAAAAAAAAAAUgCQElk4AAIAAAA6wvc1zzAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP/7kGQAAAKyHsyVJMAAOAy3uqAUAFT9LU1Zt4AIukIiwwAgAAAA9HIgBAEAwgyaBAghk56oAwtO7JkyaeeIiIjP//EeyER/4iLu71jAwCFQIFDiwff4Jh/iAEAQ/UCAIBj/lwfB8Hw+CAIAgCADB8HwfSCAIOplz/0kwAADgAQYA/5znv//////5CEIT///v/yf5CfnIRuQn/n////kOc5znP/8jeggHADAMDh8Ph5/AAAAAYUp5aDYUTi1QAWFMPETMjUzsuArMZyNpdpzhQkN4CjB1E0a1CAN6BImTqNREhUBOI6RumQD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VUGGs+aekMvGM3PjsPOSzGGX/k8itdaQuloUGu9ZjcFVuxavjjrs1jqzOSiP3pTupUqy6bpN3Zmr//VjjWZuig/v///8thqJz3////0s1dd/pU3/u6f////////+v2f//+XMfA6H/F1pN//hYSf/jzygAAYAAAImCEhz0feHViByqpZUsyg6zqBqru2XRcFL1IlLD5DUjhVONqVDYZyqGAhyqLqBdAIRxJEekhJ0sr1Wq2NBTqGoay0Yk891bf9rWrr+2/mvrX4tv1/9t+sF7aJQVBUGgaiUFn/lg5wad8SgqCo//7kmQ5D/OLLctnYeAAMMAYjeAIAIAAAaQAAAAgAAA0gAAABOt21ttt0CYKwoDQlBUFQVOlQViXxYGj3EQNA0e1A19YK1/EQNf/lf//5Y9wa//+CtVMQU1FMy45OS4zVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVU=");
//-- Customize this next for your page or get lazy and use "body".
var cntnrNode = document.querySelector ("#mainArea");
if (typeof cntnrNode === "undefined") console.error ("TM: Container node not found.");
else {
var wordObsrv = new MutationObserver (alertOnWord);
wordObsrv.observe (document.body, {childList: true, subtree: true} );
}
function alertOnWord (mutationRecords) {
mutationRecords.forEach (muttn => {
if (muttn.type === "childList" && typeof muttn.addedNodes === "object") {
muttn.addedNodes.forEach (newNode => {
/*-- Restrict the kinds of nodes watched for better performance
and/or to avoid false positives.
*/
if (newNode.nodeName === "DIV" || newNode.nodeName === "SPAN" || newNode.nodeName === "P") {
if (watchRegx.test (newNode.textContent) ) {
console.log ("Found new instance of target term!");
alrtSound.play ();
}
}
} );
}
} );
}
As it stands, I cannot get "2 credits" to make any notification sounds via Regex, such as shown below, but I have been able to get just "credits" to work:
var watchRegx = /\b2 credits\b/i;
Here is the HTML of the specific part of the page where "2 credits" lies on the site:
<span class="grey black-text lighten-2 credit-counter"><span class="remaining">2</span> credits</span>
The nature of the HTML indicates that this might not be as simple as using a Regex with "2 credits." Maybe there is an easy solution. Any and all advice would be wonderful. Thanks in advance.
I simply changed the RegEx code to var watchRegx = /2 credits/; A simple enough solution. Thanks for all the feedback
Here, we might want to separately capture our desired substrings then replace it:
.+?<span class="remaining">([0-9]+)?<\/span>(.+?)<\/span>
Our desired digits are in this capturing group:
([0-9]+)
and the second part is in this group:
(.+?)
Test
const regex = /.+?<span class="remaining">([0-9]+)?<\/span>(.+?)<\/span>/gm;
const str = `<span class="grey black-text lighten-2 credit-counter"><span class="remaining">2</span> credits</span>`;
const subst = `$1$2`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log(result);
DEMO

How to remove a pattern in JS Regex?

The following code hides all webpages of a certain website and mocks the website.
let sites = ['mako.co.il', 'walla.co.il'];
for (let i = 0; i < sites.length; i++) {
if (window.location.href.indexOf(sites[i]) != -1 ) {
alert(` Enough with this ${sites[i]} garbage! `);
}
}
It displays domain.tld this way:
"Enough with this domain.tld garbage!".
How could I strip away the .tld, so the final outcome would be:
"Enough with this domain garbage!".
A /[domain]#.2,/ regex might unmatch tld's like .com or co.uk and only "domain" will appear on the alert, but I don't know how to implement such regex to the sites[i] in the confirm.
Do you know?
It depends how complex your strings can get, but a simple match for domains could be something as follows:
str.replace(/(\.[a-zA-Z]{1,3}){1,2}/, '')
This will work for most examples of "domain.com", "domain.co.uk", "domain.es". You might be able to find a better regex, but the idea would be the same.
Need to say, that it's a long and ugly way, but I want to show you, that it's possible without regex:
function splitDomain(str) {
var beforeDomain = str.split(" domain");
var afterDomain = beforeDomain[1].split(" ").splice(1, 1);
beforeDomain.splice(1, 1);
beforeDomain.push("domain")
afterDomain.forEach(function(item) {
beforeDomain.push(item);
})
var final = beforeDomain.join(" ")
console.log(final);
}
splitDomain("Enough with this domain.tld shit!");
splitDomain("Enough with this domain.co.uk shit!");
splitDomain("Enough with this domain.com shit!");

title casing and Abbreviations in javascript

I am trying to Titlecase some text which contains corporate names and their stock symbols.
Example (these strings are concatenated as corporate name, which gets title cased and the symbol in parens): AT&T (T)
John Deere Inc. (DE)
These corporate names come from our database which draws them from a stock pricing service. I have it working EXCEPT for when the name is an abbreviation like AT&T
That is return, and you guessed it right, like At&t. How can I preserve casing in abbreviations. I thought to use indexof to get the position of any &'s and uppercase the two characters on either side of it but that seems hackish.
Along the lines of(pseudo code)
var indexPos = myString.indexOf("&");
var fixedString = myString.charAt(indexPos - 1).toUpperCase().charAt(indexPos + 1).toUpperCase()
Oops, forgot to include my titlecase function
function toTitleCase(str) {
return str.replace(/([^\W_]+[^\s-]*) */g, function (txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
}
Any better suggestions?
A better title case function may be
function toTitleCase(str) {
return str.replace(
/(\b.)|(.)/g,
function ($0, $1, $2) {
return ($1 && $1.toUpperCase()) || $2.toLowerCase();
}
);
}
toTitleCase("foo bAR&bAz a.e.i."); // "Foo Bar&Baz A.E.I."
This will still transform AT&T to At&T, but there's no information in the way it's written to know what to do, so finally
// specific fixes
if (str === "At&T" ) str = "AT&T";
else if (str === "Iphone") str = "iPhone";
// etc
// or
var dict = {
"At&T": "AT&T",
"Iphone": "iPhone"
};
str = dict[str] || str;
Though of course if you can do it right when you enter the data in the first place it will save you a lot of trouble
This is a general solution for title case, without taking your extra requirements of "abbreviations" into account:
var fixedString = String(myString).toLowerCase().replace(/\b\w/g, String.toUpperCase);
Although I agree with other posters that it's better to start with the data in the correct format in the first place. Not all proper names conform to title case, with just a couple examples being "Werner von Braun" and "Ronald McDonald." There's really no algorithm you can program into a computer to handle the often arbitrary capitalization of proper names, just like you can't really program a computer to spell check proper names.
However, you can certainly program in some exception cases, although I'm still not sure that simply assuming that any word with an ampersand in it should be in all caps always appropriate either. But that can be accomplished like so:
var titleCase = String(myString).toLowerCase().replace(/\b\w/g, String.toUpperCase);
var fixedString = titleCase.replace(/\b\w*\&\w*\b/g, String.toUpperCase);
Note that your second example of "John Deere Inc. (DE)" still isn't handled properly, though. I suppose you could add some other logic to say, put anything word between parentheses in all caps, like so:
var titleCase = String(myString).toLowerCase().replace(/\b\w/g, String.toUpperCase);
var titleCaseCapAmps = titleCase.replace(/\b\w*\&\w*\b/g, String.toUpperCase);
var fixedString = titleCaseCapAmps.replace(/\(.*\)/g, String.toUpperCase);
Which will at least handle your two examples correctly.
How about this: Since the number of registered companies with the stock exchange is finite, and there's a well-defined mapping between stock symbols and company names, your best best is probably to program that mapping into your code, to look up the company name by the ticker abbreviation, something like this:
var TickerToName =
{
A: "Agilent Technologies",
AA: "Alcoa Inc.",
// etc., etc.
}
Then it's just a simple lookup to get the company name from the ticker symbol:
var symbol = "T";
var CompanyName = TickerToName[symbol] || "Unknown ticker symbol: " + symbol;
Of course, I would be very surprised if there was not already some kind of Web Service you could call to get back a company name from a stock ticker symbol, something like in this thread:
Stock ticker symbol lookup API
Or maybe there's some functionality like this in the stock pricing service you're using to get the data in the first place.
The last time I faced this situation, I decided that it was less trouble to simply include the few exceptions here and there as need.
var titleCaseFix = {
"At&t": "AT&T"
}
var fixit(str) {
foreach (var oldCase in titleCaseFix) {
var newCase = titleCaseFix[oldCase];
// Look here for various string replace options:
// http://stackoverflow.com/questions/542232/in-javascript-how-can-i-perform-a-global-replace-on-string-with-a-variable-insi
}
return str;
}

jQuery $.inArray returns -1 when it should be 0

Hell All,
I have an odd problem:
//dataText hold current language data that's gathered from another function
//pick one to test it out
//if english data gathered
var dataText = ["Data uploads"];
//if french data gathered
var dataText = ["Envois de données"];
function lang_lib(lang) {
var data_fre = [13, 'Envois de données'];
var data_eng = [14, 'Data uploads'];
var data_lang, rep_lang;
switch(lang) {
case "English":
data_lang = data_eng;
data_rep = rep_eng;
break;
case "Français":
data_lang = data_fre;
data_rep = rep_fre;
break;
default:
$('table.infobox tbody').append('<tr><td id="lang-fail"><ul class="first last"><li>User language is not available</li></ul></td></tr>');
};
this.data_uploads = data_lang[1];
}
_lang = new lang_lib($('#toplinks-language').text());
//if lang_lib("English")
alert($.inArray(_lang.data_uploads, dataText)); // 0
//if lang_lib("Français")
alert($.inArray(_lang.data_uploads, dataText)); // -1
I shortened the code but it should give a general idea of what I'm trying to achieve.
I know it seems weird why I would be using the same data in two arrays but the data_fre and data_eng have language specific dataText info plus other language specific data as well. dataText will have non-specific language data which is why I'm testing it agains data_fre or data_eng to find which language to use.
I can't figure out why it would return -1 because I have other languages set (with special character too like Russian text) and they all return 0.
Appreciate the help :)
-1 means false. 0 means 'at position 0'. Without knowing more about the data coming in, I expect it is working properly.
Strings do not match numbers.
Simple Test
var arr = [13, 'Envois de données'];
console.log($.inArray(13,arr)); // 0 - matches as a number
console.log($.inArray("13",arr)); // -1 - matches as a string
Ok I figured out what it was.
I used $.trim() in the function that collects data for dataText. Since I couldn't see any leading or trailing spaces when I would alert() it was confusing me why it wouldn't work.
This explains why $.inArray() wouldn't match "Envois de données" with "Envois de données ".
Thanks again everybody for taking a look :)

JavaScript Replace all odd behavior

I want this code:
function renderTemplate(temp,content){
for (var i in temp){
replace = new RegExp("["+i+"]",'g');
content = content.replace(i,temp[i]);
}
return content;
}
var temp = {'status':'ok','id':150};
var content = "your status is [status], again! your status is [status], and your id is [id], yes[id]";
alert(renderTemplate(temp,content));
To genrate me this string:
your status is ok, again! your status is ok, and your id is 150, yes 150
Instead, I get:
your ok is [status], again! your status is [status], and your 150 is [id], yes[id]
Look where the ok was placed....
you can run it here: http://jsfiddle.net/v9vzd/
Thanks
Although Adrian Lang's fine answer should get you going, I would argue that you're not taking the best approach. Compiling regexes from a variable can be awkward when it comes to escaping, and it's generally slower performance-wise.
If it were me, I would take advantage of passing a function to replace():
function renderTemplate(temp, content) {
return content.replace(/\[([^[\]+)\]/g, function ($0, key) {
return temp[key];
});
}
Working demo: http://jsfiddle.net/AKsHb/
This works because the sub-expression capture, ([^\]]+) is passed to the replacing function as the second argument — labelled key in our function above — and this matches anything between a literal [ and ].
Try the following code:
function renderTemplate(temp,content){
for (var i in temp){
replace = new RegExp("\\["+i+"\\]",'g');
content = content.replace(replace,temp[i]);
}
return content;
}
var temp = {'status':'ok','id':150};
var content = "your status is [status], again! your status is [status], and your id is [id], yes[id]";
alert(renderTemplate(temp,content));
You didn’t use the RegExp object you created. Furthermore, square brackets create a character class, so oyu have to escape the square bracket (and in the RegExp constructor call, you have to escape the escaping backslash, so it is two backslashes).

Categories

Resources