js replace function not working within Snowflake UDF (but works fine in js previewer) - user-defined-functions

I'm trying create a Snowflake UDF to remove all non-numerics from a number string, like this:
create or replace function fnValidAusMobile(STRIN string)
returns string
language javascript
strict
as
'
var strIn = STRIN.replace(/\D/g,"")
return strIn
'
;
However, when I test it, I can see the regex is not working, because the below returns this: '+61 401 111-111'
SELECT fnValidAusMobile('+61 401 111-111')
Strangely, when I use a js previewer, the regex works fine, so I'm baffled.
Any clues? Are there different rules / syntax for regex when used within a Snowflake UDF?
TIA.

Could you write the regexp with double slashes?
create or replace function fnValidAusMobile(STRIN string)
returns string
language javascript
strict
as
'
var strIn = STRIN.replace(/\\D/g,"")
return strIn
'
;

The problem is about escaping. If you change the ' (single quote) to '$$' (double dollar sign) it should work fine.
create or replace function fnValidAusMobile(STRIN string)
returns string
language javascript
strict
as
$$
var strIn = STRIN.replace(/\D/g,"")
return strIn
$$
;

Related

How to escape single quote on MSSQL query into JDBC variable

Using JDBC at Jmeter I need to escape single quote performed on variable.
My original query is:
select id from [Teams] where name = '${team}'.
But, when I got a team like: Ain M'lila, the query is not executed
What I tried, and not working is:
DECLARE #NevName nvarchar
SET #NevName = REPLACE({${team}, '''', ''''''')
select id from [test8].[Team] where name = #NevName
Any solution is appreciated
In order to escape a single quote you need to add another single quote to it
In particular your case you can escape ' with an extra ' using __groovy() function like:
${__groovy(vars.get('team').replaceAll("\'"\, "''"),)}
Demo:
thanks to Dmitri T for his efforts, but the solution for me was:
JSR223 PreProcessor: and inside:
String userString = vars.get("team");
String changedUserString = userString.replace("'","''");
vars.put("teamChanged", changedUserString);
and then used as into the query:
select id from [test8].[Team] where name = '${teamChanged}'

Search Query Parameter

I want to search email which contains '+' in it. for example
something like this myemail.subdomain+1#domain.com.
URL - https://example.com?searchKey=myemail.subdomain+1#
I am using Laravel, this parameter is fetched from route using
$request->get('searchKey');
but it's converting '+' to ' ' ,
as a result i am getting
searchKey as myemail.subdomain 1#
which leads to improper result.
Any help?
PHP assumes that + from GET request is a space. Right encoded plus symbol is %2B.
You have to just prepare string from request to save plus symbol:
$searchKey= urlencode(request()->get('searchKey'));
In your case you'll get # as %40. Then you can replace plus with correct code and decode it. But then be careful with usual spaces!
$searchKey = urlencode(request()->get('searchKey'));
$searchKey = urldecode(str_replace('+', '%2B', $searchKey));
https://www.php.net/manual/en/function.urlencode.php
https://www.php.net/manual/en/function.urldecode.php
P.S. I suppose it is not the best soulution, but it should work.
P.P.S. Or, if you can prepare plus as a %2B before it will be at search parameter, do it

How to remove amp; from URL

I am getting a URL that contains amp;. Is there any way to remove this as currently I tried URLDecode function, but It's not working. Do I need to remove It using simple string replacement or Is there any better way to do this?
As #Lankymart pointed out URLDecode only works on URL-encoded characters (%26), not on HTML entities (&). Use a regular string replacement to change the HTML entity & into a literal ampersand:
url = Replace(url, "&", "&")
In Angular I added amp; to the params names
this.activatedRoute.queryParams.subscribe(params => {
this.user_id = params['user_id'];
this.practice_id = params['amp;practice_id'];
this.patient_id = params['amp;patient_id'];
});

XQuery looking for text with 'single' quote

I can't figure out how to search for text containing single quotes using XPATHs.
For example, I've added a quote to the title of this question. The following line
$x("//*[text()='XQuery looking for text with 'single' quote']")
Returns an empty array.
However, if I try the following
$x("//*[text()=\"XQuery looking for text with 'single' quote\"]")
It does return the link for the title of the page, but I would like to be able to accept both single and double quotes in there, so I can't just tailor it for the single/double quote.
You can try it in chrome's or firebug's console on this page.
Here's a hackaround (Thanks Dimitre Novatchev) that will allow me to search for any text in xpaths, whether it contains single or double quotes. Implemented in JS, but could be easily translated to other languages
function cleanStringForXpath(str) {
var parts = str.match(/[^'"]+|['"]/g);
parts = parts.map(function(part){
if (part === "'") {
return '"\'"'; // output "'"
}
if (part === '"') {
return "'\"'"; // output '"'
}
return "'" + part + "'";
});
return "concat(" + parts.join(",") + ")";
}
If I'm looking for I'm reading "Harry Potter" I could do the following
var xpathString = cleanStringForXpath( "I'm reading \"Harry Potter\"" );
$x("//*[text()="+ xpathString +"]");
// The xpath created becomes
// //*[text()=concat('I',"'",'m reading ','"','Harry Potter','"')]
Here's a (much shorter) Java version. It's exactly the same as JavaScript, if you remove type information. Thanks to https://stackoverflow.com/users/1850609/acdcjunior
String escapedText = "concat('"+originalText.replace("'", "', \"'\", '") + "', '')";!
In XPath 2.0 and XQuery 1.0, the delimiter of a string literal can be included in the string literal by doubling it:
let $a := "He said ""I won't"""
or
let $a := 'He said "I can''t"'
The convention is borrowed from SQL.
This is an example:
/*/*[contains(., "'") and contains(., '"') ]/text()
When this XPath expression is applied on the following XML document:
<text>
<t>I'm reading "Harry Potter"</t>
<t>I am reading "Harry Potter"</t>
<t>I am reading 'Harry Potter'</t>
</text>
the wanted, correct result (a single text node) is selected:
I'm reading "Harry Potter"
Here is verification using the XPath Visualizer (A free and open source tool I created 12 years ago, that has taught XPath the fun way to thousands of people):
Your problem may be that you are not able to specify this XPath expression as string in the programming language that you are using -- this isn't an XPath problem but a problem in your knowledge of your programming language.
Additionally, if you were using XQuery, instead of XPath, as the title says, you could also use the xml entities:
"" for double and &apos; for single quotes"
they also work within single quotes
You can do this using a regular expression. For example (as ES6 code):
export function escapeXPathString(str: string): string {
str = str.replace(/'/g, `', "'", '`);
return `concat('${str}', '')`;
}
This replaces all ' in the input string by ', "'", '.
The final , '' is important because concat('string') is an error.
Well I was in the same quest, and after a moment I found that's there is no support in xpath for this, quiet disappointing! But well we can always work around it!
I wanted something simple and straight froward. What I come with is to set your own replacement for the apostrophe, kind of unique code (something you will not encounter in your xml text) , I chose //apos// for example. now you put that in both your xml text and your xpath query . (in case of xml you didn't write always we can replace with replace function of any editor). And now how we do? we search normally with this, retrieve the result, and replace back the //apos// to '.
Bellow some samples from what I was doing: (replace_special_char_xpath() is what you need to make)
function repalce_special_char_xpath($str){
$str = str_replace("//apos//","'",$str);
/*add all replacement here */
return $str;
}
function xml_lang($xml_file,$category,$word,$language){ //path can be relative or absolute
$language = str_replace("-","_",$language);// to replace - with _ to be able to use "en-us", .....
$xml = simplexml_load_file($xml_file);
$xpath_result = $xml->xpath("${category}/def[en_us = '${word}']/${language}");
$result = $xpath_result[0][0];
return repalce_special_char_xpath($result);
}
the text in xml file:
<def>
<en_us>If you don//apos//t know which server, Click here for automatic connection</en_us> <fr_fr>Si vous ne savez pas quelle serveur, Cliquez ici pour une connexion automatique</fr_fr> <ar_sa>إذا لا تعرفوا أي سرفير, إضغطوا هنا من أجل إتصال تلقائي</ar_sa>
</def>
and the call in the php file (generated html):
<span><?php echo xml_lang_body("If you don//apos//t know which server, Click here for automatic connection")?>

Check for a valid guid

How can you check if a string is a valid GUID in vbscript? Has anyone written an IsGuid method?
This function is working in classic ASP:
Function isGUID(byval strGUID)
if isnull(strGUID) then
isGUID = false
exit function
end if
dim regEx
set regEx = New RegExp
regEx.Pattern = "^({|\()?[A-Fa-f0-9]{8}-([A-Fa-f0-9]{4}-){3}[A-Fa-f0-9]{12}(}|\))?$"
isGUID = regEx.Test(strGUID)
set RegEx = nothing
End Function
This is similar to the same question in c#. Here is the regex you will need...
^[A-Fa-f0-9]{32}$|^({|()?[A-Fa-f0-9]{8}-([A-Fa-f0-9]{4}-){3}[A-Fa-f0-9]{12}(}|))?$|^({)?[0xA-Fa-f0-9]{3,10}(, {0,1}[0xA-Fa-f0-9]{3,6}){2}, {0,1}({)([0xA-Fa-f0-9]{3,4}, {0,1}){7}[0xA-Fa-f0-9]{3,4}(}})$
But that is just for starters. You will also have to verify that the various parts such as the date/time are within acceptable ranges. To get an idea of just how complex it is to test for a valid GUID, look at the source code for one of the Guid constructors.
In VBScript you can use the RegExp object to match the string using regular expressions.
Techek's function did not work for me in classic ASP (vbScript). It always returned True for some odd reason. With a few minor changes it did work. See below
Function isGUID(byval strGUID)
if isnull(strGUID) then
isGUID = false
exit function
end if
dim regEx
set regEx = New RegExp
regEx.Pattern = "{[0-9A-Fa-f-]+}"
isGUID = regEx.Test(strGUID)
set RegEx = nothing
End Function
there is another solution:
try
{
Guid g = new Guid(stringGuid);
safeUseGuid(stringGuid); //this statement will execute only if guid is correct
}catch(Exception){}

Resources