I have an array where each element corresponds to an alphanumeric string, lets say :
userIds : ['Ab526', 'shvx23', '23636dsd']
I want to convert it into such a format so that I can pass this list of strings to IN clause of mySQL query as something like :
Select * from Users where userIds in '(...)';
I tried using array.join() and many other methods, suggested somewhere or the other but all in vain.
var userIds = ['Ab526', 'shvx23', '23636dsd']
var ids = userIds.join(',');
var query = 'Select * from Users where userIds in (' + ids + ')';
console.log(query);
which results in :
Select * from Users where userIds in ('Ab526, shvx23, 23636dsd');
If anyone could suggest a solution as how can I achieve what I want to, it would be of great help.
You could map the quoted values and join later.
var userIds = ['Ab526', 'shvx23', '2363\'6dsd'],
result = userIds.map(function (a) { return "'" + a.replace("'", "''") + "'"; }).join();
console.log(result);
You could use reduce on the array:
var userIds = ['Ab526', 'shvx23', '23636dsd'];
var clause = userIds.reduce(
function (cl , a, currIndex, arr)
{
return cl +
(currIndex == 0 ? "" : ",")
+"'"+ a + "'"+
(currIndex == arr.length-1 ? ")" : "") ; } , "(" );
console.log(clause );
You can use the following code :
var userIds = ['Ab526', 'shvx23', '23636dsd'];
var ids = '';
userIds.forEach(function(entry,index) {
ids += (index == 0) ? entry : ',' + entry;
});
console.log(ids);
Or a simple one liner
const userIds = [12,13,14,15];
const query = `Select * from Users where userIds in ('${userIds.join("','")}')`;
console.log(query)
This worked for me for the same issue:
var myList = [1, 2, 3]
var listAsString = myList.toString()
var queryList = "(" + listAsString + ")"
SQL Query is like so:
WHERE number IN queryList
let tickers = ['AAPL', 'MSFT']
const inStmt = "('" + tickers.join("','") + "')"
This will give you the result inStmt == ('AAPL','MSFT') which can be later on used as:
const QUERY = `select x from Y where Y.z in ${inStmt}`
Please note, that if you have numbers, not strings, single quotes must be removed:
let tickers = [1, 2, 3]
const inStmt = "(" + tickers.join(",") + ")"
Related
I have the following string :
DetailsParameters = "Id=1,UserId=1,2,3"
In entity framework stored procedure I am trying to split the above string as :
"Id=1" and "UserId=1,2,3"
Currently, I have the following code which is splitting the above mentioned string at comma which is incorrect.
if (DetailsParameters != "")
{
List<Details> adlist = new List<Details>();
DetailsParameters.Split(',').ToList().ForEach(delegate (string s)
{
adlist.Add(new Details()
{
AlarmLogId = AlarmLogId,
ParameterKey = s.Substring(0, s.IndexOf('=')),
ParameterValue = s.Substring(s.IndexOf('=') + 1, (s.Length - (s.IndexOf('=') + 1)))
});
});
context.Details.AddRange(adlist);
No need to get too complicated about it, you could do something like this:
//var DetailsParameters = "Id=1,UserId=1,2,3";
//var DetailsParameters = "UserId=1,2,3,Id=1";
var indexOf = DetailsParameters.IndexOf("UserId=");
//if the index of "UserId=" is at the start, it should find the other word "Id=" to split
if (indexOf == 0) indexOf = DetailsParameters.IndexOf("Id=", "UserId=".Length);
var firstParameter = DetailsParameters.Substring(0, indexOf);
var secondParameter = DetailsParameters.Substring(indexOf, DetailsParameters.Length - firstParameter.Length);
var firstParameterValue = firstParameter.Split('=')[1].Split(new string[] {","}, StringSplitOptions.RemoveEmptyEntries);
var secondParameterValues = secondParameter.Split('=')[1].Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
I'm making an API call to coinmarket cap and looping through a range, in a Google spreadsheet of crypto tickers.
The code is as follows:
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("test");
var r = sheet.getRange('B2:B17').getValues();
for (var i = 0; i < r.length; i++) {
symbol = r[i][0];
url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest?symbol=' + symbol + '&convert=USD&CMC_PRO_API_KEY=8192e0b9-fda4-4668-9251-3dfded3bdc2f';
//url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest?symbol=BTC&convert=USD&CMC_PRO_API_KEY=abcdetc'
var resp = UrlFetchApp.fetch(url);
var result = JSON.parse(resp.getContentText());
var price = result.data.BTC.quote.USD.price;
sheet.getRange(2 + i, 3).setValue(price);
This works but it provides, obviously, only the price for Bitcoin because BTC is in the var price line.
Instead of BTC I want to have + symbol + so that the code can loop through all the different symbols. I have tried this:
var price = result + "." + data + "." + symbol + "." + quote + "." + USD + "." price
This does not work. I have tried other various uses of "" which were also unsuccessful and also attempted to concatenate string separately.
How can this be done correctly?
Thank you in advance!
You may try something like this:
string.concat(string1, string2, ..., stringX)
or
var arr = ['a1', 'b1', 'c1'];
console.log(arr.join(',')); // 'a1,b1,c1'.
Explicit typecast can be done as,
var price = ([String(result), String(data), String(symbol), String(quote), String(USD), String(price)]).join(".")
var price = result.data.BTC.quote.USD.price;
Should be replaced with a similar code that covers your variable name:
var price = result.data[symbol].quote.USD.price;
Can someone please help me to write a JS method which takes a String value like
/Content/blockDiagram/0/bundle/0/selectedBundle
/Content/blockDiagram/1/bundle/1/selectedBundle
/Content/blockDiagram/0/bundle
and convert it to
/Content/blockDiagram[1]/bundle[1]/selectedBundle
/Content/blockDiagram[2]/bundle[2]/selectedBundle
/Content/blockDiagram[1]/bundle
It is basically taking the number in the path and increment it by 1 and then changing the structure of the string.
My attempt
function setReplicantPartListOptions(list) {
list = "/" + list;
var index = list.lastIndexOf("/");
var tempString = list.substring(0, index);
var index2 = tempString.lastIndexOf("/");
var initialString = list.substring(0, index2);
var result = tempString.substring(index2 + 1, index) var middlevalue = parseFloat(result) + 1
var lastString = list.substring(index, list.length);
list = initialString + "[" + middlevalue + "]" + lastString;
return list;
}
simple regular expression with capture group with replace
var str = "/Content/blockDiagram/0/bundle/0/selectedBundle"
var updated = str.replace(/\/(\d+)/g, function (m, num) {
var next = +num + 1; // convert string to number and add one
return "[" + next + "]"; //return the new string
})
console.log(updated)
String.replace(RegExp, callback(match, contents)) is the callback version of String.replace().
In my case, the first parameter of callback function is the result/match. It takes the match and converts it to number using + operator, and then increment it by one. Finally, I add [ ] around the value and return it!
let str = "/Content/blockDiagram/0/bundle/0/selectedBundle"
console.log(
str.replace(/\b\d+\b/g, match => `[${ +match + 1 }]`)
);
var str = "/Content/blockDiagram/0/bundle/0/selectedBundle"
console.log(
str.replace(/\/(\d+)\//g, function(_,num) { return `[${++num}]`})
)
I have a string like:
my_str = "select * from users where id = ? and name = ?;"
I also have an array to replace '?'
var arr = [1,'test']
I wanted to replace first ? with 1 and second ? with 'test' in
jQuery/JavaScript dynamically. There can be a number of ? in string.
Note this question has no relation with MySQL the query I have written is just a string.
For a more dynamic option, where replace is an array containing the replacements in order:
const string = 'select * from users where id = ? and name = ?;'
const replace = [1, 'test']
let index = 0
const output = string.replace(/\?/g, () => replace[index++])
console.log(output)
use replace method multiple times for replacing.
var my_str = "select * from users where id = ? and name = ?;"
my_str = my_str.replace("?","1"); //replaces first "?"
my_str = my_str.replace("?","test"); //replaces second "?"
alert(my_str);
Using the replace function you can do that, just use replace multiple times to replace both '?'.
var my_str = "select * from users where id = ? and name = ?;"
var arr = [1,'test']
my_str = my_str.replace("?",arr[0]).replace("?",arr[1]);
console.log(my_str);
use replace() multiple times
var r = "select * from users where id = ? and name = ?;".replace("?", '1').replace('?','test');
console.log(r);
and if you have an array of values to replace the '?':
var arr = [1,'test']
var r = "select * from users where id = ? and name = ?;"
for(i=0; i<arr.length; i++){
r = r.replace('?',arr[i]);
}
console.log(r);
Get index of ? and put into a array, then write a function to replace.
var str = "select * from users where id = ? and name = ?;"
var indices = [];
for(var i=0; i<str.length;i++) {
if (str[i] === "?") indices.push(i);
}
str = replaceAt(str,0,"1");
str = replaceAt(str,1,"Jonh");
alert(str);
function replaceAt(str, index, replacement) {
return str.substr(0, indices[index]) + replacement+ str.substr(indices[index] + 1, str.length);
}
https://jsfiddle.net/vuph31/hgbms2s1/1/
I have an object like this :
myDataObject = {
name : 'Nikola Tesla',
birth : ['10 July 1856','10. Juli 1856'],
nation : ['Serbian','Serbisch'],
knownFor : ['Alternating current',' Zweiphasenwechselstrom']
}
And two string patterns like these :
var englishStr = '#name#, born #birth[1]# , #nation[1]# best known for his contributions to #knownFor[1]#';
var deutschStr = '#name#, geboren #birth[2]#, #nation[2]# Erfinder, der für seine Beiträge zur #knownFor[2]# bekannt';
Now I want to replace #properties# marked like this.
I could do it easily if there was no multilanguage indicator like [1] or [2] smth. similar to this :
$.each(myDataObject , function(n, v){
englishStr = englishStr.replace('#'+ n +'#' , v )
});
So what can I do about the #prop[i]# ? Thank you
One way would go from the string to the data object instead of looping through all the keys.
var myDataObject = {
name : 'Nikola Tesla',
birth : ['10 July 1856','10. Juli 1856'],
nation : ['Serbian','Serbisch'],
knownFor : ['Alternating current',' Zweiphasenwechselstrom']
};
var englishStr = "#name#, born #birth[1]# , #nation[1]# best known for his contributions to #knownFor[1]#";
var re = /#([^\[#]+)\[?(\d+)?\]?#/; //Looks for #STRING# or #STRING[NUMBER]#
var test;
while ( (test=re.exec(englishStr))!==null) { //Keep looking for matches in the string
var key = test[1]; //get the key to the object
var index = test[2]; //get the index if there
var item = myDataObject[key]; //get reference to the item in the object
if (index!==undefined && item) { //if we have an index, look up the value from array
index = parseInt(index,10)-1; //arrays are zero index, so need to subtract one
item = item[index]; //get the string
}
englishStr = englishStr.replace(re, item || "N/A"); //make the replacement in the string with the data from the object
};
I suggest you try a slightly different approach here. Instead of looping over the myDataObject blindly trying to replace values, first pull out the values that need replacing, then replace them with their values.
var regex = /#(.*?)(?:\[(\d*)])?#/g;
while(match = regex.exec(englishStr)){
var matchStr = match[0];
var data = myDataObject[match[1]];
if(match[2] !== undefined){
data = data[match[2] - 1];
}
englishStr = englishStr.replace(matchStr, data);
}
DEMO: http://jsfiddle.net/35jZM/
see if this might help
$.each(myDataObject , function(n, v){
if(typeof v == 'object'){
$.each(v , function(index, value){
englishStr = englishStr.replace('#'+ n +'[' + index + ']' + '#' , v[index-1] );
});
}
englishStr = englishStr.replace('#'+ n +'#' , v )
});
Demo
There might be better solutions but I'd do something like this:
myDataObject = {
name: 'Nikola Tesla',
birth: ['10 July 1856', '10. Juli 1856'],
nation: ['Serbian', 'Serbisch'],
knownFor: ['Alternating current', ' Zweiphasenwechselstrom']
};
// English: 0, Deutsch: 1
var language = 0;
var str = "#name#, born #$birth# , #$nation# best known for his contributions to #$knownFor#";
$.each(myDataObject, function (n, v) {
str = str.replace('#' + n + '#', v);
str = str.replace('#$' + n + '#', v[language]);
});
alert(str);
Fiddle
You could also pass capture groups in a regex replace to a callback function:
(take note that if the arrays in your translation strings are indexed from 1 you'll have to add that to $2)
englishStr.replace(/#(.+?)(?:\[(\d+)\])?#/g, function($0, $1, $2){
return $2 === undefined ? myDataObject[$1] : myDataObject[$1][$2];
});
DEMO