How to output Javascript string with character encoding - javascript

So - I have a string in javascript liks so:
var foo = "Hello™";
I need to print this out in HTML (via JS) so it looks like this:
Hello™
Sounds easy, but I obviously am missing something cause I can't figure out a simple solution for it yet.
EDIT - here is more code:
var label = document.createElement('label');
var foo = selectData.options[i][1]; // this is "Hello&trade";
label.innerHTML = foo;
container.appendChild( label );

Just append it into the innerHTML property.
innerHTML will html encode the given input and that append it to the node.
var foo = "Hello™";
document.getElementById('label').innerHTML = foo;
<label id="label"></label>

First separate the '&trade' and check for it in an if-statement and then give var the value of the hexcode equivalent which is 'u2122' then the rest of the code should do the work.
String.prototype.hexEncode = function(){
var hex, i;
var result = "";
for (i=0; i<this.length; i++) {
hex = this.charCodeAt(i).toString(16);
result += ("000"+hex).slice(-4);
}
return result
}
String.prototype.hexDecode = function(){
var j;
var hexes = this.match(/.{1,4}/g) || [];
var back = "";
for(j = 0; j<hexes.length; j++) {
back += String.fromCharCode(parseInt(hexes[j], 16));
}
return back;
}
var str = "\u2122";
var newStr = (str.hexEncode().hexDecode());
var foo = "Hello" + newStr;
console.log(foo);

Related

Add and remove separators to urls by javascript

I have links on page and want mask them. I want,
that at onLoad all points in urls (which are in href) will be replaced with something like "|",
so instead of
link
there is somehting like
link.
Then, at onClick replacements should be reversed to make links working again.
Need help to get this code to work:
function mask() {
var str = document.getElementByName("a");
var x = str.attributes.href.value.replace('.', '"|"');
document.getElementsByTagName("a").attributes.href.value = x;
}
function unmask(){
var str = document.getElementByName("a");
var x = str.attributes.href.value.replace('"|"', '.');
document.getElementsByTagName("a").attributes.href.value = x;
}
<body onLoad="mask()">
link
</body>
You have to use the getElementsByTagName method:
function mask() {
var a = document.getElementsByTagName('a');
for (var i = 0; i < a.length; i++) {
a[i].attributes.href.value = a[i].attributes.href.value.replace(/\./g, '"|"');
}
}
function unmask() {
var a = document.getElementsByTagName('a');
for (var i = 0; i < a.length; i++) {
a[i].attributes.href.value = a[i].attributes.href.value.replace(/"\|"/g, '.');
}
}
<body onLoad="mask()">
link
</body>
There are several issues in your code:
document.getElementByName("a") is not valid
str.attributes.href.value is not valid
You need to go global replace to replace all the . with | and vice-versa.
function mask() {
var str = document.getElementsByTagName("a")[0];
var x = str.href.replace(/\./g, '"|"');
str.href = x;
}
function unmask(){
var str = document.getElementsByTagName("a")[0];
var x = str.href.value.replace(/"|"/g, '.');
str.href = x;
}
<body onLoad="mask()">
link
</body>

Javascript not printing variable as expected

For the following javascript
for (i = 0; i < agentIds.length; i++) {
var agentId = agentIds[i];
var variable1 = "isWrapup_"+agentId;
alert(variable1);
var text2 = "var isWrapup = JSON.parse(${"+variable1+"});";
alert(text2);
}
The first alert is printed as: isWrapup_efdbf4e71c9c6997eb705a71a6819b78
The second alert is printed as : var isWrapup = JSON.parse('+variable1+');
I'm expecting to print it as : var isWrapup = JSON.parse('isWrapup_efdbf4e71c9c6997eb705a71a6819b78')
What have I done wrong here?
The text formatting needs to be corrected, concat works better in these situations, here is why. Try:
for (i = 0; i < agentIds.length; i++) {
var agentId = agentIds[i];
var variable1 = "isWrapup_"+agentId;
alert(variable1);
var str1 = "var isWrapup = JSON.parse(${"
var str2 = "});"
var text2 = str1.concat(variable1,str2);;
alert(text2);
}
All you need to do currently is remove that '$' from the the picture and thats it.
var text2 = "var isWrapup = JSON.parse({" + variable1 + "});"; // works fine here : https://www.javascript.com/try
Also, you are unintentionally using an Escape_character#JavaScript
The Point-to-Point Protocol uses the 0x7D octet (\175, or ASCII: } )
as an escape character
In which case you can try something like this in your code :
var text2 = "var isWrapup = JSON.parse({{" + variable1 + "}});";
Hope it helps.

How to get cursor position in rich:editor richfaces by javascript

I have a rich:editor
<rich:editor id="editor" width="1000" height="300"
value="#{emailTemplateHome.instance.emailTemplateContent}"
theme="advanced">
</rich:editor>
and javascript function
function change(){
var val = document.getElementById("#{rich:clientId('editor')}");
if(val != null){
var component = val.component;
var content = component.tinyMCE_editor.getContent();
var position = content.slice(0, val.positionedOffset).length;
var result = content.substr(0,position) + "{chuc_vu}" + content.substr(position);
component.tinyMCE_editor.setContent(result);
}
}
but var position is not defined.
How can i get position of current cursor ???
Thanks in advance
If you only want to insert things at the current position you can use this:
component.tinyMCE_editor.execCommand('mceInsertContent', false, "insert text");
If you want to do something with the cursor position that's going to be tricky, since the position in the editor doesn't correspond to the position in the content (the content has HTML tags in it). You can get the position this way:
component.tinyMCE_editor.selection.getBookmark().start
val.positionedOffset is a function that returns an array, I'm not sure what you were using that for (not to mention that slice(0,x).length = x)
Writing something after cursor position:
function writeAfterCursor(element) {
var bm =tinyMCE.activeEditor.selection.getBookmark().start;
var content= tinyMCE.activeEditor
.getContent();
content= strip(content);
var res = content.split("");
var res1= [];
var res2= [];
for(i=0; i < bm; i++){
res1[i]=res[i];
}
var j=0;
for(i=bm; i < res.length; i++){
res2[j]=res[i];
j++;
}
var content1= res1.join("");
var content2= res2.join("");
content = content1+ element.value+content2;
tinyMCE.activeEditor.setContent(content);
tinyMCE.activeEditor.selection.moveToBookmark(bm);
}
function strip(html)
{
var tmp = document.createElement("DIV");
tmp.innerHTML = html;
return tmp.textContent || tmp.innerText || "";
}

appending values to textbox using for loop javascript

I am trying to add values to a textbox when looping through an array when checking checkboxes but as it is at the moment getting undefined.
Advice perhaps as to why the values are 'undefined'
var txtBoxValues = [];
$(document).on("click", "input[name=chkRelatedTopics]", function () {
var nameAdminUser = $(this).val();
var txtBox = document.getElementById("txtTraningTopics");
txtBox.value = '';
txtBoxValues.push(nameAdminUser);
for (var i in txtBoxValues) {
var str = txtBoxValues[i].value;
txtBox.value += str + '; ';
}
});
nameAdminUser is already a string, so don't take .value from it.
You could replace
var str = txtBoxValues[i].value;
with
var str = txtBoxValues[i];
But instead of using this loop, and assuming you don't want, as I suppose, the last ";", you could also do
txtBox.value = txtBoxValues.join(';');
nameAdminUser seems to be a String and in your for loop you expect an object. What if you simply do:
for (var i in txtBoxValues) {
var str = txtBoxValues[i];
txtBox.value += str + '; ';
}

Javascript to render kbd tagged elements

I would like to write a (Javascript?) function to be included in HTML pages that allows me to render the function arguments tagged as kbd separated by "+"s and able to take an arbitrary number of input arguments.
So, for example, fnRenderKBD(Ctrl+X, Y, Z) would render as Ctrl+X+Y+Z.
The important thing is that the function should be able to take a variable number of arguments.
Is it possible to write such a function (if so, how)? I have next to no knowledge of JS.
My answer at the bottom is not the best thing I have ever written. A better solution would look something like:
function fnRenderKBD(elem, keysToDisplay) {
var delimiter = '';
var content = null;
for(var i = 0, length = keysToDisplay.length; i < length; i++) {
var renderedKey = document.createElement('kbd');
renderedKey = setText(renderedKey, keysToDisplay[i]);
if (i > 0) {
elem.appendChild(document.createTextNode('+'));
}
elem.appendChild(renderedKey);
}
}
function setText(elem, text) {
if (elem.textContent){
elem.textContent = text;
}else{
elem.innerText = text;
}
return elem;
}
(function() {
var keys = [
'Ctrl+X',
'Y',
'Z'
];
var elem = document.getElementById('display');
fnRenderKBD(elem, keys);
}());​
Demo: http://jsfiddle.net/wPg7z/
Something like this should work:
function fnRenderKBD(elem, keysToDisplay)
{
var delimiter = '';
var content = '';
for(var i = 0, length = keysToDisplay.length; i < length; i++) {
content+= delimiter + '<kbd>' + keysToDisplay[i] + '</kbd>';
delimiter = '+';
}
elem.innerHTML = content;
}
(function() {
var keys = [
'Ctrl+X',
'Y',
'Z'
];
var elem = document.getElementById('display');
fnRenderKBD(elem, keys);
})();
​
Demo: http://jsfiddle.net/gTYxP/1/

Categories

Resources