How not to hardcode regex values to a string replace in lodash? - lodash

let test = L.replace( '[[Hi, Fred]]', /,|\[|\]/g, '' )
// => Hi fred
As you see this code removes all [ , and ].
How could I pass those characters to be removed, so they are not hardcoded but passed for example, from a function argument ?

You can escape the characters with _.escapeRegExp and then use a character class to remove the characters you don't want.
function removeChars(string, chars) {
return _.replace(string, new RegExp('[' + _.escapeRegExp(chars) + ']', 'g'), '');
}
function removeChars(string, chars) {
return _.replace(string, new RegExp('[' + _.escapeRegExp(chars) + ']', 'g'), '');
}
console.log(removeChars('[[Hi, Fred]]', ',[]'));
<script src="https://cdn.jsdelivr.net/lodash/4.13.1/lodash.min.js"></script>
Or use _.reject to filter out characters that are included in a blacklist.
function removeChars(string, chars) {
return _.reject(string, _.partial(_.includes, chars)).join('');
}
function removeChars(string, chars) {
return _.reject(string, _.partial(_.includes, chars)).join('');
}
console.log(removeChars('[[Hi, Fred]]', ',[]'));
<script src="https://cdn.jsdelivr.net/lodash/4.13.1/lodash.min.js"></script>

Related

how to remove all html characters in snowflake, dont want to include all html special characters in query (no hardcoding)

Want to remove below kind of characters from string..pl help
'
&
You may try this one to remove any HTML special characters:
select REGEXP_REPLACE( 'abc&def³»ghi', '&[^&]+;', '!' );
Explanation:
REGEXP_REPLACE uses regular expression to search and replace. I search for "&[^&]+;" and replace it with "!" for demonstration. You can of course use '' to remove them. More info about the function:
https://docs.snowflake.com/en/sql-reference/functions/regexp_replace.html
About the regular expression string:
& is the & character of a HTML special character
[^&] means any character except &. Tthis prevents to REGEXP to replace all characters between the first '&' char and last ';'. It will stop when it see second '&'
+ means match 1 or more of preceding token (any character except &)
; is the last character of a HTML special character
CREATE or REPLACE FUNCTION UDF_StripHTML(str varchar)
returns varchar
language javascript
strict
as
'var HTMLParsedText=""
var resultSet = STR.split(''>'')
var resultSetLength =resultSet.length
var counter=0
while(resultSetLength>0)
{
if(resultSet[counter].indexOf(''<'')>0)
{
var value = resultSet[counter]
value=value.substring(0, resultSet[counter].indexOf(''<''))
if (resultSet[counter].indexOf(''&'')>=0 && resultSet[counter].indexOf('';'')>=0)
{
value=value.replace(value.substring(resultSet[counter].indexOf(''&''), resultSet[counter].indexOf('';'')+1),'''')
}
}
if (value)
{
value = value.trim();
if(HTMLParsedText === "")
{
HTMLParsedText = value
}
else
{
if (value) {
HTMLParsedText = HTMLParsedText + '' '' + value
}
}
value=''''
}
counter= counter+1
resultSetLength=resultSetLength-1
}
return HTMLParsedText';
to call this UDF :
Select UDF_StripHTML(text)

How to check if a textbox has a value in it in vue

I'm trying to create a form and in that form only allowed numbers and text. You can't have ., , or a space any where in the textbox.
These are the codes I've tried but they haven't worked.
if([".", ",", " "].indexOf(this.name) == 1) return true;
and
if(this.name == '.' || this.name == ',' || this.name == ' ') return true;
Try using this.name.includes('.')
if (this.name.includes('.') || this.name.includes(',')) {
return true
}
Nothing to do with Vue - Vue isn't a form validator.
You need RegExp to test against the field's value. Assuming, as seems to be the case from your question, this is stored in this.name, you could do:
if (/[^\da-z]/i.test(this.name)) return false; //contains invalid input

How can I parse user input decimals based on the current locale in React Native, using a dot or comma for the decimal separator?

I have a number input that pops up a "numeric" text input in React Native.
In many locales this brings up a numeric pad with a comma for decimal separation, instead of a dot. This results in inputs like "100,1" instead of "100.1".
JavaScript's Number(value) only works with dot decimals, not commas. How can I determine the user's current format in order to properly parse the input?
This function will parse a decimal input based on the current locale, using react-native-localize:
import { getNumberFormatSettings } from "react-native-localize";
export function parseLocaleNumber(stringNumber: string) {
const { decimalSeparator, groupingSeparator } = getNumberFormatSettings();
return Number(
stringNumber
.replace(new RegExp(`\\${groupingSeparator}`, "g"), "")
.replace(new RegExp(`\\${decimalSeparator}`), "."),
);
}
For good measure, this complementary function provides toFixed functionality based on locale:
export function toFixedLocale(value: number, numDigits: number) {
const standardFixedString = value.toFixed(numDigits);
const { decimalSeparator } = getNumberFormatSettings();
if (decimalSeparator === ",") {
return standardFixedString.replace(".", ",");
} else {
return standardFixedString; // Locale matches JavaScript default
}
}
(parseLocaleNumber based on https://stackoverflow.com/a/42213804/152711)

How to search within Sphinx results using partial words?

I have a form and when I enter a value, I want to get the results on submit;
If I search for fish and I have a fishing value I want to get all the data that contain the fish value;
In my code, I get the results that I need only if I enter the full fishing word;
I am searching for the full expression and also for each word from the expression;
$sphinx_search = Yii::app()->search;
$sphinx_search->setSelect('*');
$sphinx_search_final = '';
$sphinx_search_query = trim($this->q);
if (strlen($sphinx_search_query) > 0) {
$sphinx_search_query = str_replace('-', ' ', $sphinx_search_query);
$keys = explode(' ', $sphinx_search_query);
foreach ($keys as $k => $key) {
if ($key) {
$keys[$k] = $key;
} else {
unset($keys[$k]);
}
}
if (count($keys) > 0) {
$sphinx_search_final = ' #(position_name,employer_name,employer_first_name,employer_last_name,employer_position) ' . $sphinx_search_query .
' #(position_name,employer_name,employer_first_name,employer_last_name,employer_position) ' . implode('|', $keys);
}
}
Either enable min_prefix_len or min_infix_len
to get explicit substring matching capablities.
Do also check enable_star as that changes how exactly it behaves.
Alternativly maybe stemming is what you looking for? Enabled via morphology

How to restrict typing hyphen into extjs numberfield?

Currently extjs numberfield is allowing '-' hyphen otherthan numbers into the field. how to restrict that from typing? if i give custom vtype validation it is checking only after i submit that.
use autoStripChars and remove hyphen from allowed in initComponent. corrected code below.
autoStripChars: true,
initComponent: function() {
var me = this,
allowed;
me.callParent();
me.setMinValue(me.minValue);
me.setMaxValue(me.maxValue);
// Build regexes for masking and stripping based on the configured options
if (me.disableKeyFilter !== true) {
allowed = me.baseChars + '';
if (me.allowDecimals) {
allowed += me.decimalSeparator;
}
/* removed code
if (me.minValue < 0) {
allowed += '-';
}
*/
allowed = Ext.String.escapeRegex(allowed);
me.maskRe = new RegExp('[' + allowed + ']');
if (me.autoStripChars) {
me.stripCharsRe = new RegExp('[^' + allowed + ']', 'gi');
}
}
}
You need to create custom VType. VType validation is called after any change in the textfield and you have ability to configure what characters are allowed to be entered:
http://docs.sencha.com/ext-js/4-0/#!/api/Ext.form.field.VTypes
Take a look at xxxMask property.
You could also use a regular Textfield with a maskRe config.
maskRe: /[0-9]/
Similar to #lagnat's reply which is a whitelist you can blacklist characters using stripCharsRe config.
stripCharsRe: /-/
If you are wanting to restrict negative values.
minValue: 0
{
minValue: 0,
autoStripChars: true,
allowExponential: false
}