Use Go to read a file for use in javascript rendering - javascript

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.

Related

Correct way to convert your JavaScript function into a string so it can be inserted into innerHTML

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.

Convert php's htmlspecialchars() with javascript

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)`

Single quote or double quote in javascript

I always see a write style in javascript but I don't know why code like this.
For example, I have a variable.
var topic = "community";
And when I learned javascript I saw someone coded in jQuery like this, some code in section.
:contains("' + topic + '")
But I think it can code just like this.
:contains(topic)
Or
:contains("topic")
What the differences between above three ?
:contains("topic")
this search for elements that contains "topic" string
where as
var topic = "community";
:contains(topic)
topic here becomes "community"..so it searchs for element that contains "community";
well for this
:contains("' + topic + '")
i guess the code is incomplete..
$('div:contains("' + topic + '")')..; //div for example sake
this becomes
$('div:contains("community")')..; //<-- just to make sure the string is encoded with `""`
:contains("' + topic + '") will look for the string '(VALUE of topic)', including the single quotes.
:contains(topic)
will look for the value of topic, with no surrounding quotes.
:contains("topic")
will look for literally topic.
There is no difference between single quotes and double quotes, both are used to mark an element as a string.
var s = "hello"
var m = 'hello'
m === s // true
the other example refers to escaping a string, in the case of:
contains("' + topic + '")
topic actually references a variable and not a string, therefore the quotes must be escaped in order for the program to get access to the value of the variable. otherwise it would not read the value of the variable topic but simply print the string "topic".
Single quotes vs double quotes usually has to do with whether or not string replacement will happen, but in JS it doesn't matter as far as I know
the difference between the 3 is that the first one is a variable assignment where string replacement can happen. the second one is passing a string as an argument and the third one is passing the variable or constant topic
var topicOne = "Community1";
function write(toOutput) {
document.write(toOutput);
}
write(topicOne);
write("topicOne");
write('topicOne');
so here is what the 3 will output:
Community1
topicOne
topicOne
In PHP however the same code will act differently because the double quote implies string replacement
<?php
$topicOne = "community1";
$topicTwo = "community2$topicOne";
function write($toOutput) {
print $toOutput;
}
write($topicOne);
write("$topicOne");
write('$topicOne');
write($topicTwo);
write("$topicTwo");
write('$topicTwo');
?>
will produce a different output
community1
community1
$topicOne
community2community1
community2community1
$topicTwo
see where the difference is?

Create Regex from a string variable in javascript

var tags=["div","span","body"];
for (i=0; i<=tags.length; i++){
source = source.replace(/\&lt\;<tags[i]/i, '<span class="tags[i]"><tags[i]</span>');
}
Basically, I'm trying to put all the opening div,span and body tags around a span with a class set accordingly. But, I am having issues getting the variables inside there.
I can put lines and lines for each different tag but considering this function is called on every key press I want to keep the code as small and efficient as possible.
Or are there other alternatives? I mean it would be even better if something along these lines was possible:
source = source.replace(/\&lt\;<div|<span/i, '<span class="div|span"><div|span</span>');
But, it clearly does not get me anywhere.
You can construct your regex from a string using the RegExp object:
source = source.replace(new RegExp("\\&lt\\;<" + tags[i], "i"), '<span class="' + tags[i] + '"><' + tags[i] + '</span>');
But your idea for an alternative is also possible by capturing the tag and referencing it in the replacement:
source = source.replace(/\&lt\;<(div|span|body)/i, '<span class="$1"><$1</span>');
You can use regexes with | (equivalent of OR): () are used to get the matched elements (div, span or body), and you can get them with $1
source.replace(/<(div|span|body)/i,'<span class="$1"><$1></span>')

Trying to covert a variable into its value within a URL

I'm trying to insert a variable's value into a url, but it's not working; I'm just getting the variable not the value
'myid' and 'verif' are the variables and their values are integers.
This code inserts the url into a hidden field in a form
$('#return').val(http://pegdown.com/index.php?option=com_joom_creditspack&controller=paypal&view=paypal&layout=return&task=checkout&myid=myid&packid=1&verif=verif&jcode=xxx111xxx);
How do I write the following url so the variables 'myid' and 'verif' are converted to their values?
Well you are missing quotes so your code would not work at all.
$('#return').val("http://pegdown.com/index.php?option=com_joom_creditspack&controller=paypal&view=paypal&layout=return&task=checkout&myid=" + myid + "&packid=1&verif=" + verif + "&jcode=xxx111xxx");
You should probably use encodeURIComponent()
You need to quotes " " the strings and concat the variables +
Try
$('#return').val("http://pegdown.com/index.php?option=com_joom_creditspack&controller=paypal&view=paypal&layout=return&task=checkout&myid="+myid+"&packid=1&verif="+verif+"&jcode=xxx111xxx");
JavaScript does not support string interpolation. Try something like this.
myIdVal = encodeURIComponent(myId);
verifVal = encodeURIComponent(verif);
var url = "http://pegdown.com/index.php?option=com_joom_creditspack&controller=paypal&view=paypal&layout=return&task=checkout&myid=" + myidVal + "&packid=1&verif=" + verifVal + "&jcode=xxx111xxx";
$('#return').val(url);
A simple string works for me:
given index = 2,
`a.setAttribute("href", "myDirectory/" + index + ".jpg");` links the anchor to
"myDirectory/2.jpg", ie. the file number is taken from variable index.
Not sure if the setAttribute tolerates multiple tokens in its second parameter, but generally, this works.

Categories