JavaScript Replace Text with Image - javascript

I'm still newbie, I want to replace all 'Snowman' text in the string chain for images of snowman.
Is there any easy possibility to do this in only JS?
Ok I forgot this is important too. It gets string chains actually from my Twitch channel chat to my local server using websocket node.js. When someone comment on the Twitch channel it goes into my local server in the string chain format. What I want to do is to replace or change the comment like Snowman to actual Image of Snowman.
I have very low experience with the DOM and jQuery but if this would help I can try.
Code:
Analyzing the twitch chat:
wsTwitch.onmessage = function(event) {
let eventData = JSON.parse(event.data);
Replacing text with image:
eventData2 = eventData.text.replace(/Snowman/gi, "img src='snowman.png'");

You can try like below
eventData2 = eventData.text.replace(/Snowman/gi, "<img src='path/snowman.png' />");
This will might help you.

Try this way.
var txtArr = eventData.text.split(' ');
for(var i = 0; i < txtArr.length; i++){
if(txtArr[i] === "Snowman")
txtArr[i] = `<img src="url">`;
}
var newTxt = txtArr.join(' ');
document.getElementById("txt").innerHTML = newTxt; //replace with existing element

Related

Discord.JS Deleting a message if it contains a certain word

So I am trying too add moderation too my bot and since my server is fully SFW I am trying too make it so that my bot will delete a message if it contains an NSFW word, Here is my code. Im not sure if its correct but It is not working so I would imagine its not
message.content.includes === ("<Insert NSFW message or word here>")
message.delete(1)
Im still looking for help btw
You are doing great so far,
First I would you should create an array of NSFW words that you want to be censored
Ex:
const noNoWords = ["sex", "condum"];
After you have done that you should irritate through the array and see if the message's content includes the a NSFW word
Ex:
const noNoWords = ["sex", "condum"];
client.on("message", message => {
var content = message.content;
for (var i = 0; i < noNoWords.length; i++) {
if (content.includes(noNoWords[i])){
message.delete();
break
}
}
}
That works and all but if people type CAPS it wouldn't detect, or if people put in spaces, like t h i s. In order to fix this we need to remove all special characters and make the string lower case.
Ex:
var stringToCheck = content;
stringToCheck.replace(/\s+/g, '').toLowerCase();
Then you plug it in and it should look like this :)
const noNoWords = ["sex", "condum"];
client.on("message", message => {
var content = message.content;
var stringToCheck = content.replace(/\s+/g, '').toLowerCase();
for (var i = 0; i < noNoWords.length; i++) {
if (content.includes(noNoWords[i])){
message.delete();
break
}
}
}
if (message.content.includes("<Insert NSFW message or word here>"))
message.delete(1)

Finding a numeric ID within an URL including numbers

I've run into some problems accessing and forwarding an ID.
I successfully extracted the ID from my URL but I run into problems if the URL contains unpredictable numbers aswell.
To clear things up a bit:
My efforts to extract the ID so far (JS)
var idString = window.location.href;
idString = idString.replace(/e107/gi, "__ersetzt__");
idString = idString.replace("http://localhost/Westbomke/backendV5/", "");
idString = idString.replace(/[^0-9]+/g, "");
Some URL examples
Working:
http://localhost/Westbomke/backendV5/e107-master/e107_projekte/BMW/235_Projekt_BMW-Event/page.php Result: 235 = id
Not working:
localhost/Westbomke/backendV5/e107-master/e107_projekte/BMW/235_Projekt_BMW-Event01/page.php
localhost/Westbomke/backendV5/e107-master/e107_projekte/company1337/235_Projekt_1337Event/page.php
now if I could exclude the /******_Projekt_ Part (**** = random amount of numbers) and parse it into an Integer I would be fine, but I dont know how to do this or if it's possible.
I tried to find something on here and via google but I most likely dont ask for the right stuff.
Thanks for your time and help in advance!
You can try with:
var url = 'http://localhost/Westbomke/backendV5/e107-master/e107_projekte/BMW/235_Projekt_BMW-Event/page.php';
var id = +url.match(/\/(\d+)/)[1];
Is this URL you are working on stable in terms of structure?
If you are nto familiar with Regular Expressions and the Structure is pretty stable , then the following code will do the job for you:
var myString = "http://localhost/Westbomke/backendV5/e107-master/e107_projekte/BMW/235_Projekt_BMW-Event/page.php";
var mySplitString = myString.split("/");
var myNumber = parseInt(mySplitString[8]);
console.log(myNumber);
Adding the below Function which will provide you with a bit more flexibility.
var myString = "http://localhost/Westbomke/backendV5/e107-master/e107_projekte/BMW/235_Projekt_BMW-Event/page.php";
function getProject(myString , myDist){
var mySplitString = myString.split("/");
var myID = '';
mySplitString.forEach(function(key , index){
if(key.indexOf(myDist) > 0)
myID = parseInt(mySplitString[index]);
});
return myID;
}
var myID = getProject(myString , "Projekt");
console.log(myID);

Make a mountain out of a molehill by replacing it with JavaScript

I want to replace multiple words on a website with other words. That is, I am interested in finding all instances of a source word and replacing it with a target word.
Sample Cases:
Source | Target
Molehill => Mountain
Green => Grey
Google => <a href="http://google.com">
Sascha => Monika
Football => Soccer
This is somewhat of a half answer. It shows the basic process, but also illustrates some of the inherent difficulties in a process like this. Detecting capitalization and properly formatting the replacements would be a bit intensive (probably utilizing something like this on a case-by-case basis How can I test if a letter in a string is uppercase or lowercase using JavaScript?). Also, when dealing with text nodes, innerHTML isn't an option, so the google replacement comes out as plain text instead of HTML.
TLDR - If you have another way to do this that doesn't involve javascript, do it that way.
var body = document.querySelector('body')
function textNodesUnder(el){
var n, a=[], walk=document.createTreeWalker(el,NodeFilter.SHOW_TEXT,null,false);
while(n=walk.nextNode()) a.push(n);
return a;
}
function doReplacements(txt){
txt = txt.replace(/sascha/gi, 'monika')
txt = txt.replace(/mountain/gi, 'molehill')
txt = txt.replace(/football/gi, 'soccer')
txt = txt.replace(/google/gi, 'google')
console.log(txt)
return txt
}
var textnodes = textNodesUnder(body),
len = textnodes.length,
i = -1, node
console.log(textnodes)
while(++i < len){
node = textnodes[i]
node.textContent = doReplacements(node.textContent)
}
<div>Mountains of Sascha</div>
<h1>Playing football, google it.</h1>
<p>Sascha Mountain football google</p>
Here is the JS:
function replaceWords () {
var toReplace = [
["Green","Grey"],
["Google","<a href='http://google.com'>"]
];
var input = document.getElementById("content").innerHTML;
console.log("Input: " + input);
for (var i = 0; i < toReplace.length; i++) {
var reg = new RegExp(toReplace[i][0],"g");
input = input.replace(reg,toReplace[i][1]);
}
document.getElementById("content").innerHTML = input;
};
replaceWords();

"parsing" a text document to specific javascript format?

Edit - I think parsing it the wrong word to use, I'm actually looking to format that text file into the format I provided.
I'm working on a project and I've ran into a slight problem. I need help with mass editing a text file into a certain format. I don't really know how to do this. For example, here is the text file: http://frankerfacez.com/users.txt
That has the list of users and emotes (users without periods, emotes with). I would need that to be changed into the format of
//user
"emote":["cdn.frankerfacez.com/channel/ user / emote.png"],
For reference, this is what I need the format to be: https://dl.dropboxusercontent.com/u/23313911/CustomEmotes.js
I really don't know how easy this will be or if it is even possible, but any help would be greatly appreciated!
lines = txtFile.responseText.split("\n");
var user = null;
var emote = null;
var o = {};
for (i in lines) {
var line = lines[i];
if (line.charAt(0) != ".")
user = line;
else {
try{
emote = line.substring(1, line.legth);
var a = new Array();
eval("var cnd = new String('cdn.frankerfacez.com/channel/'+user+'/'+emote+'.png');");
a.push(cnd.toString());
eval("o."+emote+" = a;");
}catch(e){
console.error(emote + " - " + user);
console.error(e);
}
}
}
console.log(o);

Google Apps Script - Dynamically Add Remove UiApp Form Elements

I am looking to create a Ui form section in my application that will Dynamically Add Remove UiApp Form Elements. I was trying to use the example from App Script Tutorials here
This example works great as far as performing the add remove elements, but when I use the submit button to capture the values, it submits as a JSON.stringify format. When I just want to capture the values only in a text or string format that will be added to a html email.
If there is way to convert JSON.stringify to text, string or get the values only in format, I will continue to use this example.
If not I was wonder if the following Javascript HTML code can be convert into GAS code and able to capture the values for each entry in a HTML email template to using in MailApp.
http://jsfiddle.net/g59K7/
Any suggestions, examples or adjustments to the codes would be greatly appreciated.
Thank you in advance
If you don't want the result to be in a JSON object, then you can adjust the _processSubmittedData(e) function. Right now he has it writing everything to an Object, which is fine. All you have to do is have a way to parse it:
function _processSubmittedData(e){
var result = {};
result.groupName = e.parameter.groupName;
var numMembers = parseInt(e.parameter.table_tag);
result.members = [];
//Member info array
for(var i=1; i<=numMembers; i++){
var member = {};
member.firstName = e.parameter['fName'+i];
member.lastName = e.parameter['lName'+i];
member.dateOfBirth = e.parameter['dob'+i];
member.note = e.parameter['note'+i];
result.members.push(member);
}
var htmlBody = 'Group Name: ' + result.groupName;
for(var a in result.members) {
var member = result.members[a];
var date = member.dateOfBirth;
var last = member.lastName;
var first = member.firstName;
var note = member.note;
htmlBody += first + ' ' + last + ' was born on ' + date + ' and has this note: ' + note;
}
MailApp.sendEmail('fakeEmail#fake.com',"Test Subject Line", "", {htmlBody: htmlBody});
}

Categories

Resources