I'm trying to implement emoticons so for example :happy: should display an emoticon. However, the text is sanitized and does not generate the actual html.
How can I replace certain strings such as :happy: with html image?
Current attempt (replace :happy: with html):
var data = snapshot.val();
var username = data.name || "anonymous";
var message = data.text;
// REPLACE STRING WITH IMAGE
message = message.replace(":happy:", "<img src='https://s3-us-west-1.amazonaws.com/static/emoticons/1.0.jpg'>");
//CREATE ELEMENTS MESSAGE & SANITIZE TEXT
var messageElement = $("<li>");
nameElement.text(username);
messageElement.text(": "+message).prepend(nameElement);
//DISPLAY MESSAGE
messageList.append(messageElement)
Update:
I think something like text.splitText() should be used here. But I'm trying to find the best way to find the text, then split it.
Use .html() to have an element effect. .text() will just put the content without having any HTML effect
messageElement.html(": "+message).prepend(nameElement);
You can use a single detached DOM element to sanitize the inputs, then convert strings to images.
Done by setting Node.textContent[mdn] and getting Element.innerHTML[mdn] on the detached node.
Then using String.prototype.replace()[mdn] method on the resulting string.
This is library free.
var username = "anonymous",
message = "Some text with an happy <b>emoticon</b> :happy: and a sad <i>emoticon</i> :sad:.",
messageList = document.getElementById("messageList"),
sanitizer = document.createElement("p");
//CREATE ELEMENTS MESSAGE
var messageElement = document.createElement("li");
//SANITIZE TEXT
sanitizer.textContent = message;
message = sanitizer.innerHTML;
//REPLACE STRING WITH IMAGE
message = message.replace(":happy:", "<img src='https://s3-us-west-1.amazonaws.com/horde.tv/static/emoticons/1.0.jpg'>");
message = message.replace(":sad:", "<img src='https://static-cdn.jtvnw.net/emoticons/v1/86/1.0'>");
messageElement.innerHTML = username + ": " + message;
//DISPLAY MESSAGE
messageList.appendChild(messageElement);
<ul id="messageList"></ul>
Related
I'm looking to remove span tags that wrap blocks of text in an in-browser editor but am having trouble if the text contains any sort of special characters like newline '\n' or encoded characters like , • , etc.
Here's my code that works on sentences without encoded characters
function fnIgnoreThisErr(evtTargID){
// use the passed parameter
var errIdx = evtTargID.substr(evtTargID.indexOf('err-') + 4);
// buld span tag for finding
var errSpan = "span.err-" + evtTargID;
// declare the editor
var editor = CKEDITOR.instances.editor1;
// get text from the editor
var edata = editor.getData();
// find the specific span in the text
var spanData = $( edata ).find(errSpan);
// get outerHTML and innerText to use for replacement
var myCurrText = spanData[0].outerHTML;
var myNewText = spanData[0].innerHTML;
// standard js replace works if no special chars
var replace_text = edata.replace(myCurrText, myNewText); //
// sets the data back in CKEditor
editor.setData(replace_text);
}
Here's an example of the text with the span tag
myCurrText:
<span class=\"vts-warn vts-ParseFailure err-2\">Approval of ICA<br />\n GAMA requested further clarification of proposed §§25.1739 (now §25.1729) and 25.1805(b) (now §26.11(b)) requirements that ICA prepared in accordance with paragraph H.</span>
And with the span tag removed.
Approval of ICA<br />\n GAMA requested further clarification of proposed §§25.1739 (now §25.1729) and 25.1805(b) (now §26.11(b)) requirements that ICA prepared in accordance with paragraph H.
It works great on plain sentences without any encoded characters. I can switch to jQuery but couldn't get replaceWith to work either.
What am I missing here?
I figured it out. There appears to be a discrepancy between html entities and the way they are being rendered/interpreted by the browser and my JS.
i.e. The outerHTML of the span is not a character-for-character match of the text in edata.
So I just get the indexOf value for the start of the span and the length of the span node. However, due to the discrepancy mentioned, this length may include additional characters. So, next, I find the exact position of the '' tag. From there, I build a string variable that exactly matches the text that needs to be replaced.
Here's my final code. (I kept it long-form for clarity)
function fnIgnoreThisErr(evtTargID){
// use the passed parameter
var errIdx = evtTargID.substr(evtTargID.indexOf('err-') + 4);
// buld span tag for finding
var errSpan = "span.err-" + evtTargID;
// declare the editor
var editor = CKEDITOR.instances.editor1;
// get text from the editor
var edata = editor.getData();
// find the specific span in the text
var spanData = $( edata ).find(errSpan);
// extract the span class name
var spanTag = '<span class="'+spanData[0].className+'">'
// find indexOf value for the span opening tag
var spanPos = edata.indexOf(spanTag);
// get the initial length of the span.
var spanLength = spanData[0].outerHTML.length;
// get the actual text from that span length.
var spanString = edata.substring(spanPos,spanPos+spanLength);
// find the acutal position of the span closing tag
var spanClose = spanString.indexOf('</span>');
var spanTagClosePos = spanClose+7;
// extract the true text comprising the span tag
var spanStringMod = edata.substring(spanPos,spanPos+spanTagClosePos);
var spanInnerHtm = spanData[0].innerHTML;
log("errSpan: "+ errSpan);
log("errSpanClass: "+ errSpanClass);
log("spanData: "+ JSON.stringify(spanData));
log("spanPos: "+ spanPos);
log("spanTagClosePos: "+ spanTagClosePos);
log("spanStringMod: "+ spanStringMod);
log("spanInnerHtm: "+ spanInnerHtm);
var newEdata = edata.replace(spanStringMod, spanInnerHtm);
log(" newEdata: "+ newEdata);
// update the editor
editor.setData(newEdata);
}
I hope this helps someone, somewhere, at some time!
Cheers!
I'm making a messenger and my messages don't ignore HTML tags because I simply past a text from input in innerHTML of message. My code:
function Message(sender) {
...
this["text"] = "";
...
this.addText = function (text) {
this["text"] = text;
};
...
};
And here I display it:
...
var chatMessageText = document.createElement("p");
chatMessageText.innerHTML = message["text"];
...
What can I do for ignoring HTML tags in message["text"]?
Update Node#innerText property(or Node#textContent property).
chatMessageText.innerText = message["text"];
Check the difference of both here : innerText vs textContent
Refer : Difference between text content vs inner text
You can't. The point of innerHTML is that you give it HTML and it interprets it as HTML.
You could escape all the special characters, but the easier solution is to not use innerHTML.
var chatMessagePara = document.createElement("p");
var chatMessageText = document.createTextNode(message["text"]);
chatMessagePara.appendChild(chatMessageText)
I am facing problem with yui TextAreaCellEditor.
Below yui statements opens the editor with save and Cancel button on clicking the yui column.
var myTextareaCellEditor = new YAHOO.widget.TextareaCellEditor();
var myColumnDefs = [
{key:"title",label:"Title", sortable:true ,editor: myTextareaCellEditor},
];
Now my problem is when ever I specify title and save in database for example my title is "text&data<new>".
It is properly getting saving but when I open the editor containing the title text.
It display like "text&data<new>".
I wanted to remove html entities from editor.
Any help is very much appreciated.
TextareaCellEditor has a Event called "Focus", When the editor is initailized and focus is on it, the Focus function is called, You can make use of it.
var myTextareaCellEditor = new YAHOO.widget.TextareaCellEditor({
focus:function(e){
var textVal = myTextareaCellEditor.textarea.value;
textVal = decodeTEXT(textVal) ;
myTextareaCellEditor.textarea.value = textVal;
}
});
myTextareaCellEditor.textarea.value : will give the value that appears in the text area. This value you can decode using the decodeText() function and replace the textarea value.
function decodeTEXT(textVal){
textVal = textVal.replace(/&/g, '&');
textVal = textVal.replace(/>/g, '>');
textVal = textVal.replace(/</g, '<');
textVal = textVal.replace(/"/g, '"');
textVal = textVal.replace(/'/g, "'");
return textVal;
}
Hope this helps. Enjoy coding :)
I'm trying to condense two processes down in to one by having the two pages I need on one page using an iframe.
I have a page that contains a text area (used for sending an email) and then I have a purchase reference page that contains the details of someones purchase.
I'm trying to append an iframe of the purchase page to the bottom of my email page and then grab some data that's on it and insert it in to the text area.
EDIT: This is what I have so far:
Script one
//Grabs the selected purchase number
var purchaseNumber = window.getSelection();
purchaseNumber = purchaseNumber.toString();
var purchaseTitle;
var purchaseNumber;
function frameLoaded() {
purchaseTitle = window.frames['purchaseIframe'].contentDocument.getElementById ('listingTitle');
purchaseNumber = window.frames['purchaseIframe'].contentDocument.getElementById ('auctionSoldIdDisplay');
purchaseTitle = purchaseTitle.innerHTML;
purchaseNumber = purchaseNumber.innerHTML
var purchaseDetails = purchaseTitle + " - " + purchaseNumber;
insertText = insertText.replace("PURCHASEDETAILS", purchaseDetails);
}
if(purchaseNumber.length > 0){
var purchaseIframe = document.createElement('iframe');
purchaseIframe.src = 'http://www.mysite.co.nz/Admin/Listing/PurchaseDisplay.aspx?asid=' + purchaseNumber + '&submit1=++GO++';
purchaseIframe.setAttribute("height","1000");
purchaseIframe.setAttribute("width","100%");
purchaseIframe.setAttribute("id","purchaseIframe");
purchaseIframe.setAttribute("onload", "frameLoaded();");
void(document.body.appendChild(purchaseIframe));
alert(purchaseNumber);
}
Script Two
//Gather the selected template
var selectedTxt = document.getElementById('txtEmailText').value;
//Change the selected txt to a string
var insertText = selectedTxt.toString();
var purchaseTitle = window.frames['purchaseIframe'].contentDocument.getElementById ('listingTitle');
var purchaseNumber = window.frames['purchaseIframe'].contentDocument.getElementById ('auctionSoldIdDisplay');
purchaseTitle = purchaseTitle.innerHTML;
purchaseNumber = purchaseNumber.innerHTML
var purchaseDetails = purchaseTitle + " - " + purchaseNumber;
insertText = insertText.replace("PURCHASEDETAILS", purchaseDetails);
//Pasting the variable in to the textarea
document.getElementById('txtEmailText').value = insertText;
Effectively I am highlighting the purchase reference number on the page then executing this script to open the purchase page using the highlighted number. I am then grabbing the text values of the elements I need and pasting them in to the text area.
I'm still pretty new to javascript and am teaching myself as I go.
If i run the above scripts one after the other then it works like a charm, however if I try to run them together with the second in an onload() function set to the iframe then it won't.
Any help would be greatly appreciated or if you could point me in the direction of an article to help.
My first thought is that the iframe is not fully loaded before you try to get the values from it. My thought would be to try adding an onload event to your iframe and then when it loads invoke a function that grabs the value.
I would add purchaseIframe.setAttribute("onload", "frameLoaded();"); to your purchaseIframe block and then add the frameLoaded() function to your script. something like:
function frameLoaded() {
var purchaseTitle = window.frames[0].document.getElementById("listingTitle" );
var purchaseNumber = window.frames[0].document.getElementById("auctionSoldIdDisplay");
console.log(purchaseTitle.innerHTML);
console.log(purchaseNumber.innnerHTML);
}
And see if something like that grabs the right values. If it does than you can plug it in where you need it.
Am I understanding your problem correctly?
I'm using JavaScript and HTA to read data in access database (.mdb) on local but having a small issue. My JavaScript code is like this:
function miseryBusiness() {
var box = document.getElementById("lyrics");
box.innerHTML = "";
var db = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source='paramore.mdb'";
var adoConn = new ActiveXObject("ADODB.Connection");
var adoRS = new ActiveXObject("ADODB.Recordset");
adoConn.Open(db);
adoRS.Open("SELECT * from 2007_RIOT WHERE track=4", adoConn, 1, 3);
var lyrics = adoRS.Fields("lyrics").value;
box.innerText = lyrics;
adoRS.Close();
adoConn.Close();
}
I have a div in the page with id="lyrics". Function gets the specified cell's value and change's div's inner text to that value.
What I want to do is use innerHTML instead of innerText. And if I use inner HTML I get the cell's value as a single line. I want to add line breaks to the end of the each line. Also an anchor to the beginning of the text.
If I was getting the text from a .txt file I'd use
while(!lyrics.AtEndOfStream) {
box.innerHTML += '<a id="miseryBusiness">' + lyrics.ReadLine() + '<br/>';
}
but this doesn't work with access database. Or I couldn't get it to work. Any ideas?
The HTA and .mdb file I'm using: link1 link2
If the lyrics are in a Memo field with hard line-breaks then the line terminator is almost certainly <cr><lf>, so try the following:
box.innerHTML = '<a id="miseryBusiness">' + lyrics.replace(/\r\n/g, '<br/>');