I have a variable written from PHP into my javascript (using json_encode), that looks a little like this:
mappoints[x]['about'] = 'Administrator: Foo Barlt;br />Telephone: 555-4202<br />Email: bert#hotmail.com<br />Website: www.domain.com'
That I am using for a google maps map point. Using the json_encode seems to be very picky about what characters I can and cannot enter into it, so i am wondering how I can convert those special html characters into real html characters using javascript?
update
The way i am building my variable is:
var description = "<h3 style='margin: 0; padding: 0;'>" + mappoints[x]['name'] + "</h3><b>Director:</b> " + mappoints[x]['director'] + "<br/>" + mappoints[x]['about'];
The HTML in the varaible is all fine, until I add the about index. No function I have attached or tried yet seems to give me proper HTML.
You can use the dom to decode those entities for you.
mappoints[x]['about'] = 'Administrator: Foo Barlt;br />Telephone: 555-4202<br />Email: bert#hotmail.com<br />Website: www.domain.com'
mappoints[x]['about'] = $('<div/>').append(mappoints[x]['about']).text();
http://jsfiddle.net/5FTCX/
Basically when you add the html to the dom it will show the entities as the characters they represent, using .text() you can receive the data back as you'd see it in the browser as text, not html with the entities. If you want back the html you can use .html() e.g..
Would it be okay with :
return mystring.replace(/&/g, "&").replace(/>/g, ">").replace(/</g, "<").replace(/"/g, """);
From here : Convert special characters to HTML in Javascript
Just because #Musa's idea was great but needed some re-interpreting on my side, I wish to post a quick function here, that will handle htmlspecialchars great, based on #Musa's design :
function htmlspecialchars_decode(string) {
$('body').append("<span style='display:none;visibility:hidden;' id='tempText'>" + string + "</span>");
var result = $('#tempText').text();
$('#tempText').remove();
return result;
};
try this
decodeURIComponent(str) or `unescape(str)` or `decodeURI(str)`
Related
I have seen many articles about Go Arrays being used with Javascript but I am trying to do something a little different. I want to read a configuration file using Go, since it has access to the server side, and use it in a javascript function that will be rendered with the template. This is to avoid hard coding values in the JavaScript:
I want to change this:
javaString += "function isValidPrefix() {"
javaString += "forbidden_prefixes = [ \"1\", \"2\", \"3\", \"4\", \"5\", \"6\" ];"
... more javascript ...
javaString += "}"
to something that puts the prefixes in a file, so that I don't have to recompile every time I want to add a prefix.
So I tried this:
var configArr []string
configArr = LoadFile("/conf.dat")
javaString += "forbidden_prefixes = [];"
for _, eachline := range configArr {
javaString += "forbidden_prefixes.push(\" + eachline + \");"
fmt.Println(eachline)
}
eachLine prints out correctly in the for loop but forbidden_prefixes contains one element + eachLine + which I am assuming is a syntax error but even if I try to retrieve the DOM element's value to check it against, the web console says the element doesn't exist. Everything worked fine with the hardcoded values. Am I doing something wrong or is it simply just not possible?
You are building a string using literals, without using the variable you intended to use. Try this:
javaString += fmt.Sprintf("forbidden_prefixes.push(\"%s\");",eachline)
The issue indeed comes from your syntax. You escaped the quotes so the + operators are actually part of the string. Here are two possible solutions:
javaString += "forbidden_prefixes.push(\"" + eachline + "\");"
Or
javaString += fmt.Sprintf("forbidden_prefixes.push(%q);", eachline)
%q adds quotes around the value it's replaced with.
What I am trying to accomplish is to have a map that has a few locations. Whenever users click on each location, a popup will emerge with some information. I am trying to create a dynamic link inside that popup.
Below is my code in Javascript
function parseDescription(message){
var string=""
for(var i in message){
if (i=="CommunityPartner"){
string+='<span style="font-weight:bold">'+i+'</span>'+": "+message[i]+'</a>'+"<br>"
} else if (i=="WeitzCECPartner"){
string+='<span style="font-weight:bold">'+i+'</span>'+": "+message[i]+'</a>'+"<br>"
} else if (i=="PhoneNumber"){
string+='<span style="font-weight:bold">'+i+'</span>'+": "+message[i]+'</a>'+"<br>"
} else if (i=="Website"){
var link = "http://www."+message[i];
string+='<span style="font-weight:bold">'+i+'</span>'+": "+'<a href="{{link}}" >'+link+'</a>'+"<br>"
}
//string+='<span style="font-weight:bold">'+i+'</span>'+": "+message[i]+"<br>"
}
return string;
}
I keep getting this error. I think it's related to the value passed into "a href" :
Request Method: GET
Request URL: http://127.0.0.1:8000/%7B%7Blink%7D%7D
Please help
Instead of using {{link}} in the string, you can try this:
var link = "http://www." + message[i];
string += '<span style="font-weight:bold">' + i + '</span>: ' + link + '<br>';
The following syntax:
{{link}}
is incorrect, because this part was inside a string it was interpreted by the JS engine as a string.
You can use template strings (backticks `) to insert variables as string into another string. For example:
`<span style="font-weight:bold">${i}</span>:<a href="${link}" >${link}</a><br>`;
This example assumes that link and i are both variables which you want to insert dynamically into your string. If you have more questions leave a comment.
I think the problem lies in the {{link}}. Your code looks like native js and not angular or any other framework. Thus, the characters {{}} inside a string do not mean anything. The url that you get is exactly those characters, escaped. Use plain old string concatination to enter your href value.
This is what I am doing: I am building a fun in house API Voting System. I am using a client side snippet insert onto page
Like this:
<script src="domain.com/api/scripts/main.js"></script>
<div id="content-wrap" id="ac1e435e-c564-48f8-9f45-338616e7a789"></div>
Now in my main .JS I do all ajax request and modify the #content-wrap with creating new elements and inserting additional JS required to run Voting System.
However big issue I am experiencing is when I write JavaScript that I need to insert into #content-wrap I am currently writing it like this:
script.innerHTML = "$(someting).on('click', funciton(){"
+ "$.ajax({type: 'post',"
+ " url: '" + base + "/api/request', data: $('form').serialize(), "
+ "success: function(response){";
As you can see that can cause lot of issues as I build on it.
What is better way to accomplish this or is there a way i can just write my script / code and do something like this.
script.innerHTML = ConvertToString(script.js) OR ConvertToString(function X);
ConvertToString is just an expression I am using to explain what I would like to do instead of what I am doing.
Thank you, I am open to any suggestions.
I also must do this in plain JavaScript or with jQuery library so any suggestions to use VueJs, AngularJS or React will be considered as future references.
Thank you again
Additional explanation:
I would like to insert into my script element JavaScript snippet. But my snippet is about 30 lines long currently and might get bigger with time so it is very difficult to code with all the + " code " on every line that I write so that it can be inserted with innerHTML into element and executed on Client end.
So I would instead like to do something like this
element.innerHTML = mysnippetcode // but with out using + "" on each line like shown above
OR
element.append(snippet)
I hope this makes it little more clear
Solution that worked for me was using back ticks to wrap my sinppet and insert it into innerHTML of the element..
Just use the function's name without the () to convert it to a string:
function foo() {
var a = 10;
var b = 20;
var c = a + b;
return c;
}
document.write(foo);
The document.write will result in this string:
function foo() { var a = 10; var b = 20; var c = a + b; return c; }
If you only want the function's body, then you could just normally remove the first and last characters of the string.
I am not entirely sure this is what you wanted, if not, please make yourself more clear.
Alternatively, you could do an eval([insert function code here]) and there would be no need to add the code to the innterHTML of the script, read up on that function if you haven't heard of it.
Or if you want to create a function from a string, you can use new Function([name] ,[function body string]) if you need arguments you have to sandwich them between the 2 parameters.
But my snippet is about 30 lines long currently and might get bigger with time > so it is very difficult to code with all the + " code " on every line that I
write
You can use template literals if you want multi-line strings in Javascript, you simply have to replace your quotes with backticks.
See this MDN page if you are interested, or even this StackOverflow answer.
I'm trying make my own html text editor. Like you see picture. I wrote bold, italic, there is no problem.
But when i wrote code (like html code), like you see only write "Test", But I wrote in textarea <p>Test</p>
And I'm using SyntaxHighlighter plugin for display my codes.
And you see my code below
function Textarea(input, preview) {
var text = input.val().replace(/\[b\]/g, "<b>").replace(/\[\/b\]/g, "</b>")
.replace(/\[i\]/g, "<i>").replace(/\[\/i\]/g, "</i>")
.replace(/\[u\]/g, "<u>").replace(/\[\/u\]/g, "</u>")
.replace(/\[s\]/g, "<s>").replace(/\[\/s\]/g, "</s>")
.replace(/\[img\]/g, "<br/><p></p><img src='").replace(/\[\/img\]/g, "' /><br/><p></p>")
.replace(/\[link/g, "<a").replace(/URL="/g, "href='").replace(/"\]/g, "'>").replace(/\[\/link\]/g, "</a>")
.replace(/\[code/g, "<pre").replace(/type="/g, "class='brush:").replace(/"\]/g, "'>").replace(/\[\/code\]/g, "</pre>");
preview.html(text);
}
I know it cause for preview.html(text), I need also write like preview.text(text) code.
But I dont know, how can i do this?
Thanks.
a quick way is to create a element inject the html code as text, then get it back out as html, then the tags, and other characters, should then be in entity form, eg < as < etc
$('<div></div>').text(input.val()).html().replace...
But there are some issues with it, eg whitespaces maybe removed
Because of that this answer shows creating a function that you can use to encode characters, which just encodes the <,>,",',& characters. You could add other characters to the replace to extend the function.
So what you need to do is html encode the raw text given by the user, then replace the bracket entities with html, and finally set the html of the output div. Here's a simple example of that:
http://jsfiddle.net/2K97x/
String.prototype.htmlEncode = function () {
return $('<div/>').text(this).html();
};
function replaceEntities(value) {
return value.replace(/\[b\]/g, "<b>").replace(/\[\/b\]/g, "</b>")
.replace(/\[i\]/g, "<i>").replace(/\[\/i\]/g, "</i>")
.replace(/\[u\]/g, "<u>").replace(/\[\/u\]/g, "</u>")
.replace(/\[s\]/g, "<s>").replace(/\[\/s\]/g, "</s>")
.replace(/\[img\]/g, "<br/><p></p><img src='").replace(/\[\/img\]/g, "' /><br/><p></p>")
.replace(/\[link/g, "<a").replace(/URL="/g, "href='").replace(/"\]/g, "'>").replace(/\[\/link\]/g, "</a>")
.replace(/\[code/g, "<pre").replace(/type="/g, "class='brush:").replace(/"\]/g, "'>").replace(/\[\/code\]/g, "</pre>");
}
var rawValue = $('input').val();
var htmlEncoded = rawValue.htmlEncode();
var newHtml = replaceEntities(htmlEncoded);
$('div').html(newHtml);
I am trying to inject json into my backbone.js app. My json has " for every quote.
Is there a way for me to remove this?
I've provided a sample below:
[{"Id":1,"Name":"Name}]
Presumably you have it in a variable and are using JSON.parse(data);. In which case, use:
JSON.parse(data.replace(/"/g,'"'));
You might want to fix your JSON-writing script though, because " is not valid in a JSON object.
Accepted answer is right, however I had a trouble with that.
When I add in my code, checking on debugger, I saw that it changes from
result.replace(/"/g,'"')
to
result.replace(/"/g,'"')
Instead of this I use that:
result.replace(/("\;)/g,"\"")
By this notation it works.
var data = $('<div>').html('[{"Id":1,"Name":"Name}]')[0].textContent;
that should parse all the encoded values you need.
This is a simple way to replace " with what you need to change it - chars, strings etc.
function solve(input) {
const replaceWith = '"' // e.g. replace " by "
const result = input.replace(/"/g, replaceWith)
return result;
}
console.log(solve('{"x":"1","y":"2","z":"10"}')
The following works for me:
function decodeHtml(html) {
let areaElement = document.createElement("textarea");
areaElement.innerHTML = html;
return areaElement.value;
}
In my case "quot" was replaced with other characters so I found a stupid but working workaround
str.replace(/&qu/g,'').replace(/ot\;/g,'')
i used replace feature in Notepad++ and replaced " (without quotes) with " and result was valid json
IF you are using SQL then you can use:
update tablename
set payload = replace(payload, '&', chr(39))
where id = 'unique id';
If you are using python then you can use:
import html
l = [{"Id":1,"Name":"Name}]
r = html.unescape(l)