i try with Node Red to build an query to send multiple values to an influxDB from a loop with this code:
var inputArray = msg.payload;
var lenInputArray =inputArray.length;
var modbusStartRegister = 14000;
var sendString = "";
var msg93 ={};
for (i = 0; i < lenInputArray; i++) {
var actRegister = modbusStartRegister +i;
var actValue = inputArray[i];
if ( i >=1){
sendString = sendString + " ,"
}
sendString = sendString +"{register: " + actRegister +"," +"value: " + actValue +"}";
if ( i ==(lenInputArray-1)){
sendString = sendString + "]"
}
}
msg93.payload = sendString;
return msg93
But the insert in the influxDB is one line it looks at them interpreted as an complete string. How can I build or convert the string that the DB accept them as individual entry? Thanks for the help
This is because you are building a string, node an object.
You can build the array object on the fly like this:
var inputArray = msg.payload;
var lenInputArray =inputArray.length;
var modbusStartRegister = 14000;
var payload = [];
var msg93 ={};
for (i = 0; i < lenInputArray; i++) {
var temp = {};
temp.register = modbusStartRegister +i;
temp.value = inputArray[i];
payload.push(temp);
}
msg93.payload = payload;
return msg93
I have this var storing a string that represents a URL full of parameters. I'm using AngularJS, and I'm not sure if there is any useful module (or maybe with plain JavaScript) to remove the unneeded URL parameters without having to use regex?
For example I need to remove &month=05 and also &year=2017 from:
var url = "at merge ?derivate=21&gear_type__in=13&engine=73&month=05&year=2017"
Use the URLSearchParams API:
var url = "at merge ?derivate=21&gear_type__in=13&engine=73&month=05&year=2017"
var urlParts = url.split('?');
var params = new URLSearchParams(urlParts[1]);
params.delete('month');
params.delete('year')
var newUrl = urlParts[0] + '?' + params.toString()
console.log(newUrl);
The advantage of using this API is that it works with and creates strings with correct percent encoding.
For more information, see MDN Developer Reference - URLSearchParams API.
You can use this function that take 2 parameters: the param you are trying to remove and your source URL:
function removeParam(key, sourceURL) {
var rtn = sourceURL.split("?")[0],
param,
params_arr = [],
queryString = (sourceURL.indexOf("?") !== -1) ? sourceURL.split("?")[1] : "";
if (queryString !== "") {
params_arr = queryString.split("&");
for (var i = params_arr.length - 1; i >= 0; i -= 1) {
param = params_arr[i].split("=")[0];
if (param === key) {
params_arr.splice(i, 1);
}
}
rtn = rtn + "?" + params_arr.join("&");
}
return rtn;
}
var url = "at merge ?derivate=21&gear_type__in=13&engine=73&month=05&year=2017";
var url2 = removeParam("month", url);
var url3 = removeParam("year", url2);
console.log(url3);
Alternative solution with a regex
Sure you can use RegExr: ((&)year=([^&]))|((&)month=([^&]))
use:
url = url.replace(/(year=([^&]*))|(month=([^&]*))/g, '');
Read more regex :)...
function removeParam(name, url){
return url.replace('/((&)*' + name + '=([^&]*))/g','');
}
var url = "?derivate=21&gear_type__in=13&engine=73&month=05&year=2017"
function removeParam(name, _url){
var reg = new RegExp("((&)*" + name + "=([^&]*))","g");
return _url.replace(reg,'');
}
url = removeParam('year', url);
url = removeParam('month', url);
document.getElementById('url-replace').innerHTML = url;
<div id="url-replace"></div>
Using string replace:
var url = "at merge ?derivate=21&gear_type__in=13&engine=73&month=05&year=2017";
var modifiedUrl = url.replace('&month=05','').replace('&year=2017','');
console.log(modifiedUrl);
You can use the library https://www.npmjs.com/package/query-string
Convert the params to an object and then just use delete params.year delete params.month and convert it back and add it to the original url
const queryString = require('query-string');
console.log(location.search);
//=> '?foo=bar'
const parsed = queryString.parse(location.search);
console.log(parsed);
//=> {foo: 'bar'}
console.log(location.hash);
//=> '#token=bada55cafe'
const parsedHash = queryString.parse(location.hash);
console.log(parsedHash);
//=> {token: 'bada55cafe'}
parsed.foo = 'unicorn';
parsed.ilike = 'pizza';
const stringified = queryString.stringify(parsed);
//=> 'foo=unicorn&ilike=pizza'
location.search = stringified;
// note that `location.search` automatically prepends a question mark
console.log(location.search);
//=> '?foo=unicorn&ilike=pizza'
Enhnaced #Mistalis's answer.
Return the value of the last occurrence of a param
Remove the ? of the removed param was the only param
Url encoded the query params to ensure browser stately
function pruneParams(key, url) {
var urlParts = url.split('?');
var rtnUrl = urlParts[0];
var paramParts;
var paramValue;
var params_arr = [];
var queryString = decodeURIComponent(urlParts[1] || '');
if (queryString !== '') {
params_arr = queryString.split('&');
for (var i = params_arr.length - 1; i >= 0; --i) {
paramParts = params_arr[i].split('=');
if (paramParts[0] === key) {
paramValue = paramParts[1];
params_arr.splice(i, 1);
}
}
if (params_arr.length) {
var wasEncoded = url.split('&').length < 2;
rtnUrl = rtnUrl + '?' + (wasEncoded ? encodeURIComponent(params_arr.join('&')) : params_arr.join('&'));
}
}
return { url: rtnUrl, [key]: paramValue, paramCount: params_arr.length > 1 };
}
var u1 = 'http://localhost:4200/member/';
var u2 = 'http://localhost:4200/member/?ts=23423424';
var u3 = 'http://localhost:4200/member/?fooo=2342342asfasf&ts=252523525';
var u4 = 'http://localhost:4200/member?foo=234243&ts=234124124&bar=21kfafjasf&ts=223424234&dd=This Is A Line';
var u5 = 'http://localhost:4200/member?foo%3D234243%26ts%3D2242424%26bar%3D21kfafjasf%26dd%3DThis%20Is%20A%20Line';
console.log(pruneParams('ts', u1));
console.log(pruneParams('ts', u2));
console.log(pruneParams('ts', u3));
console.log(pruneParams('ts', u4));
console.log(pruneParams('ts', u5));
// {
// url: 'http://localhost:4200/member/',
// ts: undefined,
// paramCount: false,
// }
// {
// url: 'http://localhost:4200/member/',
// ts: '23423424',
// paramCount: false,
// }
// {
// url: 'http://localhost:4200/member/?fooo=2342342asfasf',
// ts: '252523525',
// paramCount: false,
// },
// {
// url: 'http://localhost:4200/member?foo=234243&bar=21kfafjasf&dd=This Is A Line',
// ts: '234124124',
// paramCount: true,
// }
// {
// url: 'http://localhost:4200/member?foo%3D234243%26bar%3D21kfafjasf%26dd%3DThis%20Is%20A%20Line',
// ts: '2242424',
// paramCount: true,
// }
Taken from #Mistalis answer but tidied up. Useful if URLSearchParams API is not available.
const removeUrlParam = function (url, param) {
var parts = url.split('?')
url = parts[0]
if (parts.length !== 2) return url
var qs = parts[1]
if (qs === '') return url
var params = qs.split('&')
for (var i = params.length - 1; i >= 0; i -= 1) {
var key = params[i].split('=')[0]
if (key === param) params.splice(i, 1)
}
return params.length ? url + '?' + params.join('&') : url
}
var url1 = removeUrlParam('/xxxxx', 'a')
var url2 = removeUrlParam('/xxxxx?a=1', 'a')
var url3 = removeUrlParam('/xxxxx?a=1&b=2', 'a')
console.log(url1, url2, url3)
my url looks something like this
/myurl?code1=abcde&code2=fghijk&code3=lmnop&code4=qrstu&code5=vwxyz (up to max of 5 code variables)
I have an onclick event where I get the code variable, eg in example above it returns 'fghijk', but I don't know the param, eg code2. So I want to do two things:
1) find and remove the param & value from my url (if my onclick variable returns 'fghijk', in the above example my url becomes, /myurl?code1=abcde&code3=lmnop&code4=qrstu&code5=vwxyz)
2) after this I want to reset the param numbers so that my code params are sequential beginning from 1, so after number 1 above executes my url should become /myurl?code1=abcde&code2=lmnop&code3=qrstu&code4=vwxyz
$('.myelement').on('click', function() {
var url = $('.myelement a').attr('href');
var codevar = $('.myelement span').text();
if(url +'contains('+codevar+')') {
// strip the param and variable from the url here
// now reset the url so code params are in number sequence
}
});
you could do something like this:
$('.myelement').on('click', function() {
var url = $('.myelement a').attr('href');
var codevar = $('.myelement span').text();
if(url.match(codevar)) {
var queryString = url.substring(url.indexOf("?") + 1);
var params = queryString.split("&");
var codeIndex = 1;
var newQuery = "";
for (var i = 0; i < params.length; i++) {
if (!params[i].match(codevar)) {
newQuery += params[i].replace(/code[0-9]/, "code" + codeIndex);
codeIndex++;
if (i < params.length - 1) {
newQuery += "&";
}
}
}
url = url.replace(queryString, newQuery).replace(/&$/, ""); //new query string with the sequential parameters
}
});
Hope this helps.
Regards,
Marcelo
var codevar = 'fghijk';
var url = $('.myelement a').attr('href');
var param = '&'+url.substring(url.indexOf('?')+1);
url = url.substring(0,url.indexOf('?')+1);
if(param.indexOf(codevar) > -1) {
var arr = param.split("&code");
param = '';
for(var i = 1;i<arr.length;i++){
if(codevar == arr[i].substring(2))
arr.splice(i, 1);
param += 'code'+i+'='+arr[i].substring(2);
if(i != arr.length-1)
param +='&';
}
$('.myelement a').attr('href',url+param);
Example:
http://jsfiddle.net/trevordowdle/b9Hmb/1/
You could split the url with the param as key.
var el = $('.myelement'),
out = $("#output");
el.on('click', function (ev) {
ev.preventDefault();
var href = el.find("a").prop("href"),
param = el.find("span").text(),
idx = href.indexOf(param),
arr = [], url;
if (idx > -1) {
arr = href.split(param); // split href[0] param href[1]
url = arr.join("mynewvalue");
out.text(url);
}
});
DEMO : http://jsfiddle.net/tive/EAsw3/
I'm trying to save a HUGE json string in my localStorage but for some reason sometimes it saves it and sometimes not, I thought I should compress it so I took an LZW implementation in js from one of the threads in stackoverflow.
The problem is when I try to localStorage.setItem() the compressed string it gives me an error "Invalid argument", any idea why or what should I do?
Edit:
this is the code I'm using:
// LZW-compress a string
function lzw_encode(s) {
var dict = {};
var data = (s + "").split("");
var out = [];
var currChar;
var phrase = data[0];
var code = 256;
for (var i=1; i<data.length; i++) {
currChar=data[i];
if (dict[phrase + currChar] != null) {
phrase += currChar;
}
else {
out.push(phrase.length > 1 ? dict[phrase] : phrase.charCodeAt(0));
dict[phrase + currChar] = code;
code++;
phrase=currChar;
}
}
out.push(phrase.length > 1 ? dict[phrase] : phrase.charCodeAt(0));
for (var i=0; i<out.length; i++) {
out[i] = String.fromCharCode(out[i]);
}
return out.join("");
}
// Decompress an LZW-encoded string
function lzw_decode(s) {
var dict = {};
var data = (s + "").split("");
var currChar = data[0];
var oldPhrase = currChar;
var out = [currChar];
var code = 256;
var phrase;
for (var i=1; i<data.length; i++) {
var currCode = data[i].charCodeAt(0);
if (currCode < 256) {
phrase = data[i];
}
else {
phrase = dict[currCode] ? dict[currCode] : (oldPhrase + currChar);
}
out.push(phrase);
currChar = phrase.charAt(0);
dict[code] = oldPhrase + currChar;
code++;
oldPhrase = phrase;
}
return out.join("");
}
this is the code that calls the compressing algorithm and saves it in LS
LOG("GetMerchantList(): Done");
var SITESVAR = unescape(data)
localStorage.setItem("MYSITES", lzw_encode(SITESVAR)); //this throws error
IWT.BuildMerchantList(SITESVAR);
I have no idea how to properly 'return' this JSON object (in JavaScript):
function callback() {
var points = '{\"points\": [';
var params = polyline.getLatLngs();
var i;
for (i = 0; i < points.length; i++) {
params = params.concat('{\"latitude\": ', points[i].lat, ', \"longitude\": ', points[i].lng, '}');
if (i < points.length - 1) {
params = params.concat(', ');
}
}
params = params.concat('] }');
return JSON.parse(params);
}
I want to catch it with something like (Objective-C):
NSString *s = [self.webView stringByEvaluatingJavaScriptFromString:#"callback();"];
Obviously this results in a NSString, what I really want is NSData to do this (Objective-C):
NSData *data = [s dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *response = [NSJSONSerialization JSONObjectWithData:data options:NSJSONWritingPrettyPrinted error:&error];
So, how to properly return the JSON?
This should do it:
function callback() {
var params = polyline.getLatLngs();
var result = [];
var i;
for (i = 0; i < params.length; i++) {
result.push({latitute: params[i].lat, longitude: params[i].long});
}
return JSON.stringify({points: result});
}
Note that JSON.parse generates an object from a string, and JSON.stringify creates a string from an object. No need to do it manually.