Javascript-Node.Js reaching dynamic body elements - javascript

I have HTML input elements with names like A[1], A[2], A[3]. I want to catch them in express this way:
var optcount = i + 1;
var columnA=req.body['A['+optcount+']'];
However it does not work.
If I have names like A1, then this works:
var columnA=req.body['A'+optcount];
Any suggestions?

For a quick hack,
var optcount = i + 1;
var prop = 'A[' + optcount + ']';
var columnA=req.body[prop];
Should work.
You should be escaping characters to have a better optimized solution, look at these -> Is there a RegExp.escape function in Javascript? and How to escape regular expression in javascript?

Related

Adding quotes to a comma separated string

What I have:
var a = "1.1.1.1,2.2.2.2,3.3.3.3"
What I need:
var a = '1.1.1.1','2.2.2.2','3.3.3.3'
What I'm trying:
var a = "1.1.1.1,2.2.2.2,3.3.3.3"
var b = a.split(",")
var c
for (var i=0;i<b.length; i++)
{
c.concat("\'").concat(b[i]).concat("\',\"")
}
What I'm actually getting with the above
"'1.1.1.1','"
I'm only able to get the first element right, how do I rectify this?
Also, in JS, is it even possible to have something like '1.1.1.1','2.2.2.2','3.3.3.3' stored in a variable?
A background to this problem:
I have an iframe whose source is a kibana query. The query in fact takes in values to a particular parameter in the above mentioned format.
Eg:
params:!('1.1.1.1','2.2.2.2')
While my db contains the param values as a string of CSV.
Eg.
"1.1.1.1,2.2.2.2,3.3.3.3"
Try this
var a = "1.1.1.1,2.2.2.2,3.3.3.3";
var b = "'" + a.split( "," ).join( "','" ) + "'";
console.log( b );
You don't need to deal with iterations for this, use a RegExp replace:
var a = "1.1.1.1,2.2.2.2,3.3.3.3";
var b = "'" + a.replace(/,/g, "','") + "'";
console.log( b );
The naive solution to your problem looks like this:
> line = '1.1.1.1,2.2.2.2,3.3.3.3'
'1.1.1.1,2.2.2.2,3.3.3.3'
> '"' + line.replace(/,/g, '","') + '"'
'"1.1.1.1","2.2.2.2","3.3.3.3"'
or if the quotes need to be reversed:
> "'" + line.replace(/,/g, "','") + "'"
'\'1.1.1.1\',\'2.2.2.2\',\'3.3.3.3\''
However, it sounds like what you need is a full-blown CSV parser, to handle cases in which you have quotes and commas and new lines and other crazy characters embedded in your input.
The naive solution seems to be in line, though, with what you were trying to do, and might illustrate why your approach fell short.
Your code works as you intended. Can you append to c without declaring?
var a = "1.1.1.1,2.2.2.2,3.3.3.3"
var b = a.split(",")
var c = ""
for (var i=0;i<b.length; b++)
{
c.concat("\'").concat(b[i]).concat("\',\"")
console.log(b)
}
You can store several values in a variables by using array for example.
If you want to get string like '"1.1.1.1","2.2.2.2","3.3.3.3"' you can use the following code:
var a = "1.1.1.1,2.2.2.2,3.3.3.3";
var b = a.split(',').map(function (str) {
return '"' + str+ '"';
}).join(',');
console.log(b);

Removing special words from Delimitted string

Ive a situation to remove some words from a delimitted string in which the last char is ¶.
That means that if the string is:
keyword1,keyword2,keyword3¶,keyword4,keyword5¶,keyword6
The output string should be:
keyword1,keyword2,keyword4,keyword6
How can we achieve that in javascript?
This is what i did but i would like to do it without looping:
var s='keyword1,keyword2,keyword3¶,keyword4,keyword5¶,keyword6';
s=s.split(',');
var t=[];
$(s).each(function(index,element){
var lastchar=element[element.length-1];
if(lastchar!='¶')
{
t.push(element);
}
});
console.info(t.join(','));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Problem can be solved using regular expressions:
var s='keyword1,keyword2,keyword3¶,keyword4,keyword5¶,keyword6';
s=s.replace(/,keyword\d+¶/g, '');
console.info(s);
You should use the filter functionality in the JS.
var _s = "keyword1,keyword2,keyword3¶,keyword4,keyword5¶,keyword6";
var _output = _s.split(",").filter(function(word){
return (word[word.length - 1] !== "¶");
}).join(",");
console.log(_output);
Regular expressions should work. They are likely slower than writing your own loops, but in most cases they are clearer and you won't notice the difference.
var s='keyword1,keyword2,keyword3¶,keyword4,keyword5¶,keyword6';
console.info('original: ' + s);
var edited = s.replace(/¶.+¶/, '');
console.info('result: ' + edited);
var s = 'keyword1,keyword2,keyword3¶,keyword4,keyword5¶,keyword6';
var t = s.split(",").filter(function(word) {
return !word.slice(-1).match(/[\u{0080}-\u{FFFF}]/gu, "");
})
console.info(t);
You can use the filter! Obviously this checks for any character that isn't ASCII. You can simply check if the last character is your ¶.
This way:
var str ='keyword1,keyword2,keyword3¶,keyword4,keyword5¶,keyword6';
var keywords = str.split(",");
for(keyword in keywords){
if(keywords[keyword].includes("¶")){
keywords.splice(keyword,1);
}
}
console.log(keywords);
PS: Every method loops to do it, you just can't see it in some forms ^^

Replace script tag that has a dynamic version number which keeps changing

I would like to remove or replace this string in an HTML file using javascript.
'<script src="../assets/js/somejs.js?1.0.953"></script>'
Trouble is, the version number "1.0.953" keeps changing so I can't use a simple string.replace
You could achieve this using the following Regex:
\?.*?\"
Or, more specifically
(\d+)\.(\d+)\.(\d+)
For matching the version number.
Utilizing the regex, you can replace the version number with a blank value.
Ok this is messy but it works...
String.prototype.replaceAnyVersionOfScript = function(target, replacement) {
// 1. Build the string we need to replace (target + xxx + ></script>)
var targetLength = target.length;
var targetStartPos = this.indexOf(target);
var dynamicStartPos = targetStartPos + targetLength;
var dynamicEndPos = this.indexOf('></script>', dynamicStartPos) + 10;
var dynamicString = this.substring(dynamicStartPos, dynamicEndPos);
var dymamicStringToReplace = target + dynamicString;
// 2. Now we know what we are looking for. We can replace it.
return this.replace(dymamicStringToReplace, replacement);
};
shellHTML = shellHTML.replaceAnyVersionOfScript('<script src="./assets/js/CloudZoom.js', '');

append single quotes to characters

I have a string like
var test = "1,2,3,4";
I need to append single quotes (' ') to all characters of this string like this:
var NewString = " '1','2','3','4' ";
Please give me any suggestion.
First, I would split the string into an array, which then makes it easier to manipulate into any form you want. Then, you can glue it back together again with whatever glue you want (in this case ','). The only remaining thing to do is ensure that it starts and ends correctly (in this case with an ').
var test = "1,2,3,4";
var formatted = "'" + test.split(',').join("','") + "'"
var newString = test.replace(/(\d)/g, "'$1'");
JS Fiddle demo (please open your JavaScript/developer console to see the output).
For multiple-digits:
var newString = test.replace(/(\d+)/g, "'$1'");
JS Fiddle demo.
References:
Regular expressions (at the Mozilla Developer Network).
Even simpler
test = test.replace(/\b/g, "'");
A short and specific solution:
"1,2,3,4".replace(/(\d+)/g, "'$1'")
A more complete solution which quotes any element and also handles space around the separator:
"1,2,3,4".split(/\s*,\s*/).map(function (x) { return "'" + x + "'"; }).join(",")
Using regex:
var NewString = test.replace(/(\d+)/g, "'$1'");
A string is actually like an array, so you can do something like this:
var test = "1,2,3,4";
var testOut = "";
for(var i; i<test.length; i++){
testOut += "'" + test[i] + "'";
}
That's of course answering your question quite literally by appending to each and every character (including any commas etc.).
If you needed to keep the commas, just use test.split(',') beforehand and add it after.
(Further explanation upon request if that's not clear).

Rewrite Javascript path String

In Javascript, I have a string for a path that looks like:
/xxx:Level1/yyy:Level2/xxx:Level3/ccc:Level4
The prefix may or may not be there for each level. I need to create a new string which eliminates the prefix on each folder level, something like:
/Level1/Level2/Level3/Level4
OK. I've done something like the following, but I think perhaps with regex it could be made more compact. How could I do that?
var aa = "/xxx:Level1/yyy:Level2/xxx:Level3/ccc:Level4"
var bb = aa.split("/").filter(String);
var reconstructed = "";
for( var index in bb )
{
var dirNames = bb[index].split(":");
if(dirNames.length==1) reconstructed += "/" + dirNames[0];
else if(dirNames.length==2) reconstructed += "/" + dirNames[1];
}
You can use regex like this:
var str = "/xxx:Level1/yyy:Level2/xxx:Level3/ccc:Level4";
var out = str.replace(/\/[^:\/]+:/g, "/");
alert(out);
This matches:
/
followed by one or more characters that is not a : or a /
followed by a :
and replaces all that with a / effectively eliminating the xxx:
Demo here: http://jsfiddle.net/jfriend00/hbUkz/
Like this:
var bb = aa.replace(/\/[a-z]+:/g, '/');
Change the [a-z] to include any characters that might appear in the prefix, or just use [^\/:].
var a = "/xxx:Level1/yyy:Level2/xxx:Level3/ccc:Level4";
var b = a.replace(/\/[^\/]*:/g, "/");
aa = aa.replace(/\/[^:\/]\:/g, "/");
This function will replace every occurence of "/xxx:" by "/" using a RE, where xxx: is a prefix.

Categories

Resources