Javascript string variable to link - javascript

I'm making a chrome extension and I want to convert my javascript string variable into a clickable link. This is what my code does right now,
var regex = /[\w]+[\/]+[\w]+#(?:\d*\.)?\d+/g;
This finds a format on a page e.g. stack/overflow#12453. I convert the regex into a string with this function
function objectToString(object) {
var stringify = "";
for (var property in object) {
stringify += object[property] + '<br>';
}
return stringify;
}
What i want to do is to make that string into a clickable link. So if there are 5 links on a page, each of the strings returned would be a clickable link to a href. Is this possible? I would gladly appreciate any help.

Try this :
var obj = new Object();
obj.link1 = "www.google.com";
obj.link2 = "www.msn.com";
$().ready(function () {
$.each(objectToString(obj).split(','), function (i) {
$("ul").append("<li>" + objectToString(obj).split(',')[i] + "</li>");
});
});
function objectToString(object) {
var stringify = "";
for (var property in object) {
stringify += object[property] + ",";
}
stringify = stringify.slice(0, stringify.length - 1);
return stringify;
}
Jsfiddle : http://jsfiddle.net/u4hghL9c/

Related

createHtmlOutputFromFile then append variable as an object from the function

I want to pass all values from Google Sheets to HTML (Google web app) by using Google-Apps-Script doGet() and append in the script to keep as global variable. Faster than html load first then use google.run.script... in my opinion
So getting an object key as a sheet_name and key values as 2D_array data
function getSheetData() {
var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets()
var object = {}
for (var i = 0; i < sheets.length; i++) {
object[sheets[i].getName()] = sheets[i].getDataRange().getValues().filter(r => r[0] !== '')
}
return object
}
in function doGet() I'm using append to add the script to the HTML
function doGet() {
var html = HtmlService.createHtmlOutputFromFile('Main')
html.append('<script> var userData = ' + getSheetData() + ' </script>')
return html
}
Still getting <script> var userData = [object Object] </script>
it should be something like <script> var userData = {key1:[2D Array],key2:[2D Array]} </script>
I also tried with string and it works fine. But can we possibly do as an object?
Thank you in advance
html.append(' var userData = ' + getSheetData() + ' ')
When appending html, the script is appending a string. The object returned by getSheetData() is coerced to a string implicitly, when using the + operator. The coercion doesn't produce a full array as string but just as [object Object].
To bypass this, you may use JSON.stringify() server side:
html.append('<script> var userData = ' + JSON.stringify(getSheetData()) + ' </script>')

javascript .data() cuts the string content by whitespace

So, I have this problem where I have a backwards-button in a webapplication. This is the javascript-code for the button:
function getPrevFunction()
{
localDBSelect("prevViews", function (prevViews)
{
if (prevViews)
{
var prevViewObject = $.parseJSON(prevViews);
var prevViewArray = prevViewObject['funcObjects'];
if (prevViewArray.length > 1)
{
var prevArrayIndex = prevViewArray.length - 2;
var actArrayIndex = prevViewArray.length - 1;
var prevFuncObject = prevViewArray[prevArrayIndex];
var prevFunc = prevFuncObject['function'];
var prevConfig = prevFuncObject['config'];
var inData = prevFuncObject['inData'];
prevViewArray.splice(actArrayIndex, 1);
if (inData !== "")
{
if (prevFunc !== "getGuiSiteList")
{
inData = "<div data-param=" + JSON.stringify(inData) + ">";
}
$('#fieldcontain')[prevFunc](inData, prevConfig);
}
else {
$('#fieldcontain')[prevFunc](prevConfig);
}
if (prevViewArray.length === 1)
{
setVisibilityForBackBtn(false); //If last..
}
prevViewObject['funcObjects'] = prevViewArray;
localDBInsert("prevViews", JSON.stringify(prevViewObject));
}
else {
setVisibilityForBackBtn(false);
}
$('#subcontainer').html("");
if(!$('#fieldcontain').is(":visible"))
{
$('#fieldcontain').show();
}
}
});
}
My problem is that I don't always get the entire content of the json-object. Eg; the json, at the beginning it looks like this:
input = {site: "GAV", location: "EG", set: "INVENTORY", binnum: "B01 T09"}
but after I have tried to fetch the json that is being passed as a data/attribute with an html-element like so:
var input = $(inData).data("param");
the value I recieve looks as follows:
input = "{"site":"GAV","location":"EG","set":"INVENTORY","binnum":"B01"
As you can se it has by some reason cut off all the characters after the whitespace, despite nothing happens between the fact that the last functions is added to the list, and that function is then called again, too be able to go backwards in the application.
I do realize that my explanation is messy and probably hard to understand, but this is the best that I can explain it.
I can provide more code if necessary.
So, I do need the entire json for the getPrevFunction (it is passed as "prevViews")
Use encodeURIComponent() and decodeURIComponent() like below
Setting the data
inData = "<div data-param=" + encodeURIComponent(JSON.stringify(inData)) + ">";
Getting the data
var input = JSON.parse(decodeURIComponent($(testDv).data('param')));
Now there will be no cuttings in the object due to whitespace.

detect for empty field in angularJS

I'm getting json data with a bunch of spaces as strings like this:
{
appNumber: " "
}
but at times i get this back
{
appNumber: "123456"
}
I want to be able to detect when it doesnt have any numerical value in it and display a dash instead
so in my controller i have:
$scope.appNumber = function() {
var appNumber = $scope.appNumber.trim();
if (!appNumber) {
return "-";
}
return $scope.appNumber;
};
in my HTML:
<div ng-bind="appNumber()"></div>
You are calling trim on the current scope function. change the name of your variable you want to trim
To return appNumber if it is a number or '-' try below
$scope.appNumber = function() {
$scope.str = "12312";
var x = + $scope.str;
if (x.toString() === $scope.str) {
return $scope.str;
}
return '-';
};
Working fiddle

Javascript Objects to XML String with multiple levels

I have a multi-dimensional Javascript Object that I can easily convert to a JSON string using a .stringify method. I'm trying to write a function to do something similar but in an XML, markup, format. The catch is I want it to be able to handle any number of dimensions.
Let's say I have the following the multi-dimensional object with values like so:
object['annualrevenues']['option0']['ID'] = 1;
object['annualrevenues']['option0']['text'] = '$50mil';
object['annualrevenues']['option1']['ID'] = 2;
object['annualrevenues']['option1']['text'] = '$100mil';
object['annualrevenues']['option2']['ID'] = 3;
object['annualrevenues']['option2']['text'] = '$200mil';
I want to build a string like so:
var xmlText = <xml><annualrevenues><option0><ID>1</ID><text>$50</text></option0></annualrevenues></xml>
That once returned as a response with contentType 'XMLDOC' will look like this:
<xml>
<annualrevenues>
<option0>
<ID>1</ID>
<text>$50</text>
</option0>
</annualrevenues>
</xml>
So I have the following function:
var xmlText = '<xml>';
xmlText += formatXMLSubObjects(objText,xmlText);
function formatXMLSubObjects(objText,xmlText){
for (prop in objText) {
if (typeof objText[prop] == 'object') {
xmlText += '<'+prop+'>';
for (subProp in objText[prop]) {
if (typeof objText[prop][subProp] == 'object') {
// Run the function again as recursion
xmlText += formatXMLSubObjects(objText[prop][subProp],xmlText);
}
else {
xmlText += '<' + subProp + '>' + objText[prop][subProp] + '</' + subProp + '>';
}
}
xmlText += '</'+prop+'>';
}
else {
xmlText += '<'+prop+'>'+objText[prop]+'</'+prop+'>';
}
}
return xmlText;
}
The problem is when the formatXMLSubObjects function returns from the second call, the original object in the first call has been overwritten and is now undefined.
Anyone able to help with this?
Move the definition of xmlText inside the function and use another variable outside to contain the initial payload, and also local variables in the for loops, otherwise they are considered global and overwritten, and don't pass your xmlText ahead to the call, but simply concatenate the result with the previous one every time.
function formatXMLSubObjects(objText) {
var xmlText = ""; // this will contain only this chunk of the object
for (var prop in objText) {
xmlText += '<'+prop+'>'; // place the tag anyway
if (typeof objText[prop] == 'object') {
xmlText += formatXMLSubObjects(objText[prop]); // if it's an object recurse
} else {
xmlText += objText[prop]; // ... otherwise just add the value (this will work only for simple values
}
xmlText += '</' + prop + '>';
}
return xmlText;
}
var xml = '<xml>';
xml += formatXMLSubObjects(obj);
xml += '</xml>';
Take a look at this fiddle: http://jsfiddle.net/vZjAP/

Get escaped URL parameter

I'm looking for a jQuery plugin that can get URL parameters, and support this search string without outputting the JavaScript error: "malformed URI sequence". If there isn't a jQuery plugin that supports this, I need to know how to modify it to support this.
?search=%E6%F8%E5
The value of the URL parameter, when decoded, should be:
æøå
(the characters are Norwegian).
I don't have access to the server, so I can't modify anything on it.
function getURLParameter(name) {
return decodeURI(
(RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
);
}
Below is what I have created from the comments here, as well as fixing bugs not mentioned (such as actually returning null, and not 'null'):
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
}
What you really want is the jQuery URL Parser plugin. With this plugin, getting the value of a specific URL parameter (for the current URL) looks like this:
$.url().param('foo');
If you want an object with parameter names as keys and parameter values as values, you'd just call param() without an argument, like this:
$.url().param();
This library also works with other urls, not just the current one:
$.url('http://allmarkedup.com?sky=blue&grass=green').param();
$('#myElement').url().param(); // works with elements that have 'src', 'href' or 'action' attributes
Since this is an entire URL parsing library, you can also get other information from the URL, like the port specified, or the path, protocol etc:
var url = $.url('http://allmarkedup.com/folder/dir/index.html?item=value');
url.attr('protocol'); // returns 'http'
url.attr('path'); // returns '/folder/dir/index.html'
It has other features as well, check out its homepage for more docs and examples.
Instead of writing your own URI parser for this specific purpose that kinda works in most cases, use an actual URI parser. Depending on the answer, code from other answers can return 'null' instead of null, doesn't work with empty parameters (?foo=&bar=x), can't parse and return all parameters at once, repeats the work if you repeatedly query the URL for parameters etc.
Use an actual URI parser, don't invent your own.
For those averse to jQuery, there's a version of the plugin that's pure JS.
If you don't know what the URL parameters will be and want to get an object with the keys and values that are in the parameters, you can use this:
function getParameters() {
var searchString = window.location.search.substring(1),
params = searchString.split("&"),
hash = {};
if (searchString == "") return {};
for (var i = 0; i < params.length; i++) {
var val = params[i].split("=");
hash[unescape(val[0])] = unescape(val[1]);
}
return hash;
}
Calling getParameters() with a url like /posts?date=9/10/11&author=nilbus would return:
{
date: '9/10/11',
author: 'nilbus'
}
I won't include the code here since it's even farther away from the question, but weareon.net posted a library that allows manipulation of the parameters in the URL too:
Blog post: http://blog.weareon.net/working-with-url-parameters-in-javascript/
Code: http://pastebin.ubuntu.com/1163515/
You can use the browser native location.search property:
function getParameter(paramName) {
var searchString = window.location.search.substring(1),
i, val, params = searchString.split("&");
for (i=0;i<params.length;i++) {
val = params[i].split("=");
if (val[0] == paramName) {
return unescape(val[1]);
}
}
return null;
}
But there are some jQuery plugins that can help you:
query-object
getURLParam
Based on the 999's answer:
function getURLParameter(name) {
return decodeURIComponent(
(location.search.match(RegExp("[?|&]"+name+'=(.+?)(&|$)'))||[,null])[1]
);
}
Changes:
decodeURI() is replaced with decodeURIComponent()
[?|&] is added at the beginning of the regexp
Need to add the i parameter to make it case insensitive:
function getURLParameter(name) {
return decodeURIComponent(
(RegExp(name + '=' + '(.+?)(&|$)', 'i').exec(location.search) || [, ""])[1]
);
}
After reading all of the answers I ended up with this version with + a second function to use parameters as flags
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)','i').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
}
function isSetURLParameter(name) {
return (new RegExp('[?|&]' + name + '(?:[=|&|#|;|]|$)','i').exec(location.search) !== null)
}
$.urlParam = function(name){
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(top.window.location.href);
return (results !== null) ? results[1] : 0;
}
$.urlParam("key");
For example , a function which returns value of any parameters variable.
function GetURLParameter(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return sParameterName[1];
}
}
}​
And this is how you can use this function assuming the URL is,
"http://example.com/?technology=jquery&blog=jquerybyexample".
var tech = GetURLParameter('technology');
var blog = GetURLParameter('blog');
So in above code variable "tech" will have "jQuery" as value and "blog" variable's will be "jquerybyexample".
You should not use jQuery for something like this!
The modern way is to use small reusable modules through a package-manager like Bower.
I've created a tiny module that can parse the query string into an object. Use it like this:
// parse the query string into an object and get the property
queryString.parse(unescape(location.search)).search;
//=> æøå
There's a lot of buggy code here and regex solutions are very slow. I found a solution that works up to 20x faster than the regex counterpart and is elegantly simple:
/*
* #param string parameter to return the value of.
* #return string value of chosen parameter, if found.
*/
function get_param(return_this)
{
return_this = return_this.replace(/\?/ig, "").replace(/=/ig, ""); // Globally replace illegal chars.
var url = window.location.href; // Get the URL.
var parameters = url.substring(url.indexOf("?") + 1).split("&"); // Split by "param=value".
var params = []; // Array to store individual values.
for(var i = 0; i < parameters.length; i++)
if(parameters[i].search(return_this + "=") != -1)
return parameters[i].substring(parameters[i].indexOf("=") + 1).split("+");
return "Parameter not found";
}
console.log(get_param("parameterName"));
Regex is not the be-all and end-all solution, for this type of problem simple string manipulation can work a huge amount more efficiently. Code source.
<script type="text/javascript">
function getURLParameter(name) {
return decodeURIComponent(
(location.search.toLowerCase().match(RegExp("[?|&]" + name + '=(.+?)(&|$)')) || [, null])[1]
);
}
</script>
getURLParameter(id) or getURLParameter(Id) Works the same : )
jQuery code snippet to get the dynamic variables stored in the url as parameters and store them as JavaScript variables ready for use with your scripts:
$.urlParam = function(name){
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (results==null){
return null;
}
else{
return results[1] || 0;
}
}
example.com?param1=name&param2=&id=6
$.urlParam('param1'); // name
$.urlParam('id'); // 6
$.urlParam('param2'); // null
//example params with spaces
http://www.jquery4u.com?city=Gold Coast
console.log($.urlParam('city'));
//output: Gold%20Coast
console.log(decodeURIComponent($.urlParam('city')));
//output: Gold Coast
function getURLParameters(paramName)
{
var sURL = window.document.URL.toString();
if (sURL.indexOf("?") > 0)
{
var arrParams = sURL.split("?");
var arrURLParams = arrParams[1].split("&");
var arrParamNames = new Array(arrURLParams.length);
var arrParamValues = new Array(arrURLParams.length);
var i = 0;
for (i=0;i<arrURLParams.length;i++)
{
var sParam = arrURLParams[i].split("=");
arrParamNames[i] = sParam[0];
if (sParam[1] != "")
arrParamValues[i] = unescape(sParam[1]);
else
arrParamValues[i] = "No Value";
}
for (i=0;i<arrURLParams.length;i++)
{
if(arrParamNames[i] == paramName){
//alert("Param:"+arrParamValues[i]);
return arrParamValues[i];
}
}
return "No Parameters Found";
}
}
I created a simple function to get URL parameter in JavaScript from a URL like this:
.....58e/web/viewer.html?page=*17*&getinfo=33
function buildLinkb(param) {
var val = document.URL;
var url = val.substr(val.indexOf(param))
var n=parseInt(url.replace(param+"=",""));
alert(n+1);
}
buildLinkb("page");
OUTPUT: 18
Just in case you guys have the url like localhost/index.xsp?a=1#something and you need to get the param not the hash.
var vars = [], hash, anchor;
var q = document.URL.split('?')[1];
if(q != undefined){
q = q.split('&');
for(var i = 0; i < q.length; i++){
hash = q[i].split('=');
anchor = hash[1].split('#');
vars.push(anchor[0]);
vars[hash[0]] = anchor[0];
}
}
Slight modification to the answer by #pauloppenheim , as it will not properly handle parameter names which can be a part of other parameter names.
Eg: If you have "appenv" & "env" parameters, redeaing the value for "env" can pick-up "appenv" value.
Fix:
var urlParamVal = function (name) {
var result = RegExp("(&|\\?)" + name + "=(.+?)(&|$)").exec(location.search);
return result ? decodeURIComponent(result[2]) : "";
};
This may help.
<script type="text/javascript">
$(document).ready(function(){
alert(getParameterByName("third"));
});
function getParameterByName(name){
var url = document.URL,
count = url.indexOf(name);
sub = url.substring(count);
amper = sub.indexOf("&");
if(amper == "-1"){
var param = sub.split("=");
return param[1];
}else{
var param = sub.substr(0,amper).split("=");
return param[1];
}
}
</script>

Categories