CREATE OR REPLACE FUNCTION instr_reverse(st string)
RETURNS string
LANGUAGE JAVASCRIPT
AS '
var temp = ST.split("")
var temp1 = temp.reverse()
var temp2 = temp1.join()
return temp2
';
function error -> unknown function reverse
As Himanshu mentioned there is a function for this: REVERSE
select REVERSE('GOKHAN');
Anyway, as I like to write JavaScript functions, I checked your script, and it worked on me:
CREATE OR REPLACE FUNCTION instr_reverse(st string)
RETURNS string
LANGUAGE JAVASCRIPT
AS '
var temp = ST.split("")
var temp1 = temp.reverse()
var temp2 = temp1.join("")
return temp2
';
select instr_reverse( 'gokhan' );
JS supports method chaining:
CREATE OR REPLACE FUNCTION PUBLIC.instr_reverse(st string)
RETURNS string
LANGUAGE JAVASCRIPT
AS '
return ST.split("").reverse().join("");
';
select PUBLIC.instr_reverse('Hello World');
-- dlroW olleH
If the goal is to reverse word order:
CREATE OR REPLACE FUNCTION instr_reverse(st string)
RETURNS string
LANGUAGE JAVASCRIPT
AS '
return ST.split(" ").reverse().join(" ");
';
select PUBLIC.instr_reverse('Hello World');
-- World Hello
Related
I have a string which contains values like
var string = A,B,C
Here I want to add single quote for each comma value, expected result should be as below
output = 'A','B','C'
My angular code is
var data = {
output : this.string.split("\',"),
}
which is giving result as
["A,B,C"]
Could anyone please help on this how can I get desired output.
I am understanding your code as
var string = "A,B,C"; // because string should be in this format.
and you just need to replace "\'," from your split function to "," which will give you an array like this
var out = string.split(",");
console.log(out);
[ 'A', 'B', 'C' ] // this is the output.
as split function searches for the given expression and split the string into array.
but if you just want to modify the string without making it in array then you can use the below trick
var out = "'" + string.replace(/,/g, "','") + "'";
console.log(out);
'A','B','C' // result as u mentioned and this is of string type.
I am currently working on my project using angularjs. I got everything already it is just that, i need to convert the dictionary list to a string separated by comma. I can only do this using python.
[{"name":"john"},{"name":"mark"},{"name":"peter"}]
I want to convert them to string
"john,mark,peter"
I would really appreciate your help. :)
.map and then .join will do
var array = [{"name":"john"},{"name":"mark"},{"name":"peter"}];
var names = array.map(function(item) {
return item.name;
}).join(',');
The map() method creates a new array with the results of calling a function for every array element. Use this to loop and then add that value to a variable.
var dict=[{"name":"john"},{"name":"mark"},{"name":"peter"}];
var string;
dict.map(function(value){
//do any stuff here
string+=value["name"]+",";
});
console.log(string);
Try map function to concatenate the values:
var dict=[{"name":"john"},{"name":"mark"},{"name":"peter"}];
var str="";
dict.map(function(a){
str+=a["name"]+",";
});
//feels ironical as question has AngularJS tag
document.getElementById("log").innerText=str;
<div id="log"></div>
You can simply iterate over each key-value pair and concat the extracted value with comma.
var obj = [{"name":"john"},{"name":"mark"},{"name":"peter"}]
var result = '';
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
result += obj[p].name + ",";
}
}
result = result.replace(/,$/g,''); // to trim trailing comma
I'm making an AngularJS filter which capitalizes each word's first letter.
It works well with a-zA-Z letters, but in my case I use also cyrillic characters and I would like to make it work.
var strLatin = "this is some string";
var strCyrillic = "това е някакъв низ";
var newLatinStr = strLatin.replace(/\b[\wа-яА-Я]/g, function(l){
return l.toUpperCase();
});
var newCyrillicStr = strCyrillic.replace(/\b[\wа-яА-Я]/g, function(l){
return l.toUpperCase();
});
Here I got some CodePen example: http://codepen.io/brankoleone/pen/GNxjRM
You need a custom word boundary that you may build using groupings:
var strLatin = "this is some string";
var strCyrillic = "това е някакъв низ";
var block = "\\w\\u0400-\\u04FF";
var rx = new RegExp("([^" + block + "]|^)([" + block + "])", "g");
var newLatinStr = strLatin.replace(rx, function($0, $1, $2){
return $1+$2.toUpperCase();
});
console.log(newLatinStr);
var newCyrillicStr = strCyrillic.replace(rx, function($0, $1, $2){
return $1+$2.toUpperCase();
});
console.log(newCyrillicStr);
Details:
The block contains all ASCII letters, digits and underscore and all basic Cyrillic chars from the basic Cyrillic range (if you need more, see Cyrillic script in Unicode ranges Wiki article and update the regex accordingly), perhaps, you just want to match Russian with А-ЯЁёа-я, then use var block = "\\wА-ЯЁёа-я
The final regex matches and captures into Group 1 any char other than the one defined in the block or start of string, and then matches and captures into Group 2 any char defined in the block.
If you use Lodash, you can use _.startCase instead of your own implementation (they do it by splitting the string into words, capitalizing the 1st character of each word and then joining them back together)
Try it:
function capitalizer(string) {
return string.split(/\s/).map(function(item){
return (item.charAt(0).toUpperCase() + item.slice(1))
}).join(' ')
}
Example
I am attempting to build a dynamic Sql query for multiple search terms. I understand in general how to use the builder, but am not sure what to do in the loop since I actually need the #term to be different each time (I think). Not just in the query, but in the anonymous type as well to match.
I could use a string.Format in the query string, but not sure how to match it in the anonymous type?
public async Task<List<Thing>> Search(params string[] searchTerms)
{
var builder = new SqlBuilder();
var template = builder.AddTemplate("SELECT * /**select**/ from ThingTags /**where**/ ");
for (int i = 0; i < searchTerms.Length; i++)
{
builder.OrWhere("value LIKE #term", new { term = "%" + searchTerms[i] + "%" });
}
...
}
in the current form the query that gets created for terms "abc" "def" "ghi" is
CommandType: Text, CommandText: SELECT * from ThingTags WHERE ( value LIKE #term OR value LIKE #term OR value LIKE #term )
Parameters:
Name: term, Value: %ghi%
Well here is one way to do the query building. I didn't realize that the parameters could be a Dictionary initially.
public async Task<List<Thing>> Search(params string[] searchTerms)
{
var builder = new SqlBuilder();
var template = builder.AddTemplate("SELECT * /**select**/ from ThingTags /**where**/ ");
for (int i = 0; i < searchTerms.Length; i++)
{
var args = new Dictionary<string, object>();
var termId = string.Format("term{0}", i.ToString());
args.Add(termId, "%" + searchTerms[i] + "%");
builder.OrWhere("value LIKE #" + termId, args);
}
...
}
You can easily create that dynamic condition using DapperQueryBuilder:
var query = cn.QueryBuilder($#"
SELECT *
FROM ThingTags
/**where**/");
// by default multiple filters are combined with AND
query.FiltersType = Filters.FiltersType.OR;
foreach (var searchTerm in searchTerms)
query.Where($"value like {searchTerm}");
var results = query.Query<YourPOCO>();
The output is fully parametrized SQL (WHERE value like #p0 OR value like #p1 OR...). You don't have to manually manage the dictionary of parameters.
Disclaimer: I'm one of the authors of this library
I was trying to use the Where and OrWhere methods of SqlBuilder for Dapper, but it is not acting like how I would expect.
The edited portion of this question is basically what I ran into. Since it didn't receive a response, I'll ask it here.
var builder = new SqlBuilder();
var sql = builder.AddTemplate("select * from table /**where**/ ");
builder.Where("a = #a", new { a = 1 })
.OrWhere("b = #b", new { b = 2 });
I expected select * from table WHERE a = #a OR b = #b
but I got select * from table WHERE a = #a AND b = #b
Is there any way to add an OR to the where clause using the SqlBuilder?
I think it's just a matter of changing the following in the SqlBuilder class to say OR instead of AND, but I wanted to confirm.
public SqlBuilder OrWhere(string sql, dynamic parameters = null)
{
AddClause("where", sql, parameters, " AND ", prefix: "WHERE ", postfix: "\n", IsInclusive: true);
return this;
}
Nevermind. I looked through the SqlBuilder code and found that if there is a mixture of Where and OrWhere, it will do the following:
Join all the AND clauses
Join all the OR clauses separately
Attach the OR clauses at the end of the AND clauses with an AND
If you don't have more than 1 OrWhere, then you won't see any OR.
I'll modify my query logic to take this into account
You have to change your query into:
var builder = new SqlBuilder();
var sql = builder.AddTemplate("select * from table /**where**/ ");
builder.OrWhere("a = #a", new { a = 1 })
.OrWhere("b = #b", new { b = 2 });
In case you want to try another alternative, DapperQueryBuilder may be easier to understand:
var query = cn.QueryBuilder($#"
SELECT *
FROM table
/**where**/
");
// by default multiple filters are combined with AND
query.FiltersType = Filters.FiltersType.OR;
int a = 1;
int b = 2;
query.Where($"a = {a}");
query.Where($"b = {b}");
var results = query.Query<YourPOCO>();
The output is fully parametrized SQL (WHERE a = #p0 OR b = #p1).
You don't have to manually manage the dictionary of parameters.
Disclaimer: I'm one of the authors of this library