I am using latinize to translate german language's special characters to English, they module work only when I pass string within single or double quotes, but not when I pass by storing them inside a variable.
import latinize from 'latinize';
ANd inside render, I console this and it works fine,
console.log('render', latinize('VfL Osnabrück'))
also when i pass my
let tag_name = 'VfL Osnabrück';
console.log('render', latinize('VfL Osnabrück'))
it will again works fine, but did not work fine when I get tag_name from my api. And complete code is below
let tag_parsing = sub_category_id.split('%20');
let tag_string = '';
for (let i = 0; i < tag_parsing.length; i++) {
tag_parsing[i];
// tag_parsing[0] == Vlf
// tag_parsing[1] == Osnabrück
console.log('latinized text', tag_parsing[i]);
tag_string += ' ' + tag_parsing[i]
}
OUTPUT
output of latinized text ==> Osnabr%C3%BCck
output of latinized text inside quotes ==> Osnabruck
I also try with .toString() but did not work
I think there may be something off with how you are attempting to process the query string from the URL.
Here's a snippet of the logic I used to process your query string in a forked codesandbox. I used a functional component for ease, but the same logic can be used in a class-based component.
// get the search string
const { search } = useLocation();
const [latinizedValue, setLatinizedValue] = React.useState("");
React.useEffect(() => {
console.log({ search });
// create search params object
const newParams = new URLSearchParams(search);
const key = newParams.get("key");
const value = newParams.get("value")?.trim();
console.log("Param", key, `"${value}"`);
console.log("latinize param:", `"${latinize(value)}"`);
setLatinizedValue(latinize(value));
}, [search]);
Demo
The font-family that i was using was not contains special german characters, and finally I changed the font-family that supports german special characters, and everything goes smooth and latinize also works fine.
Related
I am trying to implement a search using regex . To validate if the entered value is a valid regex in the search box I am using the source code from a library regex-validate (REGEX VALIDATION LIBRARY - regex-regex)
If the entered value is a valid regex then I am Parsing it to a regular expression using the source code from this library Regex-Parse) (PARSING LIBRARY - Regex Parser) to filter/search using the parsed regex.Here is a code snippet for the same
import { useState } from "react";
import "./styles.css";
import { re, RegexParser } from "./regexValidation";
export default function App() {
const [val, setVal] = useState("");
const [validRegex, setValidRegex] = useState(false);
const validateRegex = (val: string) => {
setVal(val);
if (val === "") {
setValidRegex(false);
return;
}
// to check if the entered value(val) is a valied regex in string
if (re.test(val)) {
setValidRegex(false);
// parsing the entered value(val) to a regularexpression
const convertToRegex = RegexParser(val);
//filtering logic to filter based on convertToRegex variable
} else {
setValidRegex(true);
}
};
const handleChange = (e: any) => {
validateRegex(e.target.value);
};
return (
<div className="App">
<input value={val} onChange={handleChange}></input>
<h1>{validRegex ? "inValidRegex" : "ValidRegex"}</h1>
</div>
);
}
CodeSandBox link for the regex search RegexValidationSearch
I am facing an issue when the user enters '/?/' or '/*/' the re.test(val) returns true thereby implying that it is a valid regex but when it is trying to get parsed that is this line of code const convertToRegex = RegexParser(val) it throws the following errorRegexError
Is there any way to fix this such that this line of code re.test(val) returns false when the user enters any invalid regular expression there by implying that it is an invalid regex(in string format) and hence there is no need to parse it to a regular expression
This looks like it might be an incompatibility between the two libraries you are using (ie, they have different ideas of what valid Regex is).
Easiest way to fix this (and honestly the safest too, since you're dealing with user input) is to wrap your entire parsing logic with a try/catch like this:
// to check if the entered value(val) is a valied regex in string
if (re.test(val)) {
let convertToRegex;
try {
convertToRegex = RegexParser(val);
setValidRegex(true); // only set this AFTER a successful parse.
// also note I've swapped the true / false value here.
} catch (e) {
setValidRegex(false);
}
if (convertToRegex) {
// TODO: implement filtering logic based on convertToRegex variable
}
} else {
// NOTE: it didn't parse correctly, shouldn't this be false?
setValidRegex(false); // I've changed it for you
}
Also I think(?) you've made a couple errors in how you're handling setValidRegex which I've corrected in code. Don't be optimistic and say the user input is valid regex when you haven't actually confirmed (by creating a RegexParser) that it is!
With this approach there's an argument for deleting the re.test(val) and the other library entirely since you can get what you want by simply try/catch-ing. Up to you to decide if this is a decent choice for your codebase.
I want to get the range of a custom word in my VS Code extension, if I hover on it, and if the line of text matches a pattern. This is what I've written so far:
vscode.languages.registerHoverProvider('.mylanguage', {
provideHover(document, position, token) {
// define `hoverRange` somewhere here
const hoverLineText = document.lineAt(position.line).text;
const pattern = new RegExp("\\w+\\s{0,}\\(.{0,}\\s{0,}\\)");
if(pattern.test(hoverLineText)){
hoverRange = document.getWordRangeAtPosition(position, pattern);
}
console.log(hoverRange);
//etc. ...
I am expecting that, if you write in the editor something like myFunction ( ), and you hover on any position of that string (e.g. even on the whitespace), the console will output hoverRange, which will take into account the position of the closing parenthesis ), as well.
However, if I hover on the whitespace, nothing is outputted to the console. Instead, I need to hover on myFunction, so that I can get the whole range of the string.
How can I make my VS Code extension treat myFunction ( ) as one single word?
This works for me:
let disposable3 = vscode.languages.registerHoverProvider('plaintext', {
provideHover(document, position) {
let hoverRange;
const hoverLineText = document.lineAt(position.line).text;
const pattern = new RegExp("\\w+\\s*\\(.*\\s*\\)");
if (pattern.test(hoverLineText)){
hoverRange = document.getWordRangeAtPosition(position, pattern);
if (hoverRange) return new vscode.Hover(document.getText(hoverRange), new vscode.Range(position, position));
else return null;
}
else return null;
}
});
context.subscriptions.push(disposable3);
As you can see the hover works over spaces. But the regex is too lenient so that it does pick up things like
if (asdasdasd)
while(adasd)
since those look like a function calls too.
This is my first time posting in SO, and I need help formatting numbers correctly in a calculator app that I've made using ReactJS.
Here is the link on StackBlitz.
Now, I want to achieve the formatting effect after numbers are pressed and shown in the display and arithmetic signs are added, especially when multiple arithmetics are used.
To illustrate my point, below is a sample of the current display:
123456 + 7890123 * 11111
And what I want to achieve is this:
123,456 + 7,890,123 * 11,111
I could only do this when displaying the result using the toLocaleString() function. Even then, if I pressed number/numbers and then clicking the result button twice, it will be crashed (as the display contains a comma, and the evaluation function will not process it properly).
Hopefully, someone can point me out in the right direction. Thanks.
Quick Fix
You can remove ',' before evaluating the result.
Change line 65 of Input.js to
setDisplay(evaluate(display.replace(/,/g, '')).toLocaleString());
Better Solution
Keep separate variables for Internal logical state and External Display state, where the former is valid for code and the latter is its visual representation.
You can achieve this by useEffect like this
/* --- Display.js --- */
const Display = ({ display }) => {
const [printValue, setPrintValue] = useState('')
useEffect(() => {
setPrintValue(`${display}`.replace(/[0-9]+/g, num => (+num).toLocaleString()))
}, [display])
return (
<StyledDisplay>
{' '}
<span>{printValue}</span>{' '}
</StyledDisplay>
);
};
Also, in Input.js, update line 65 in handleResult to
setDisplay(evaluate(display));
For this kind of situations, I like to use regex. Here what you can do is to use a regex that matches 3 digits and add the comma as wanted. To simplify the regex I usually reverse the string:
const original = "123456 / 98765 * 22222"
function format(str) {
const reversed = str.split('').reverse().join('')
const formatted = reversed.replace(/(\d{3})(?=\d)/gm, `$1,`)
return formatted.split('').reverse().join('')
}
console.log('original string : ', original)
console.log('result string : ',format(original))
You can use this function in your Display component, just before injecting the display prop like this
function format(str){
const reversed = str.split('').reverse().join('')
const formatted = reversed.replace(/(\d{3})(?=\d)/gm, `$1,`)
return formatted.split('').reverse().join('')
}
const Display = ({ display }) => {
return (
<StyledDisplay>
{' '}
<span>{format(display)}</span>{' '}
</StyledDisplay>
);
};
am trying to replace numbers in an array but am facing an issue which am not really able to correctly manage regarding how to correctly target the just one data I really have to change.
I'll make an example to have more accuracy on describing it.
Imagine my data array look like that:
["data", "phone numbers", "address"]
I can change numbers via following script but my first problem is that it makes no differences between the number it find in columns, for example "phone numbers" from "address" (at the moment am not using it, but should I include a ZIP code in the address it would be really be a problem)
Beside, my second and current problem with my script, is that obviosuly in the same "phone numnbers" a number may appear more times while I'd like to affect only the first block of the data - let's say to add/remove the country code (or even replace it with it's country vexillum) which I normally have like that "+1 0000000000" or "+54 0000000000"
So if a number is for example located in EU it really make this script useless: Spain is using "+34" while France "+33" and it wouldn't succeded in any case becouse it recognize only "+3" for both.
I've found some one else already facing this problems which seems to solved it wrapping the values inside a buondaries - for example like that "\b"constant"\b" - but either am wronging syntax either it does not really apply to my case. Others suggest to use forEach or Array.prototype.every which I failed to understand how to apply at this case.
Should you have other ideas about that am open to try it!
function phoneUPDATES(val)
{
var i= 0;
var array3 = val.value.split("\n");
for ( i = 0; i < array3.length; ++i) {
array3[i] = "+" + array3[i];
}
var arrayLINES = array3.join("\n");
const zero = "0";
const replaceZERO = "0";
const one = "1";
const replaceONE = "1";
const result0 = arrayLINES.replaceAll(zero, replaceZERO);
const result1 = result0.replaceAll(one, replaceONE);
const result2 = result1.replaceAll(two, replaceTWO);
const result3 = result2.replaceAll(thre, replaceTHREE);
const result4 = result3.replaceAll(four, replaceFOUR);
const result5 = result4.replaceAll(five, replaceFIVE);
const result6 = result5.replaceAll(six, replaceSIX);
const result7 = result6.replaceAll(seven, replaceSEVEN);
const result8 = result7.replaceAll(eight, replaceEIGHT);
const result9 = result8.replaceAll(nine, replaceNINE);
const result10 = result9.replaceAll(ten, replaceTEN);
const result11 = result10.replaceAll(eleven, replaceELEVEN);
Why not use a regex replace, you could do something like /(\+\d+ )/g which will find a + followed by one or more digits followed by a space, and then you can strip out the match:
const phoneNumbers = [, "+54 9876543210"]
console.log(phoneNumbers.map((num) => num.replaceAll(/(\+\d+ )/g, '')))
If you need to only target the second element in an array, i'd imagine your data looks like
const data = [["data", "+1 1234567890, +1 5555555555", "address"], ["data", "+11 111111111, +23 23232323", "address"]];
console.log(data.map((el) => {
el[1] = el[1].replaceAll(/(\+\d+ )/g, '');
return el;
}))
ok, this almost is cheating but I really didn't thought it before and, by the way does, not even actually solve the problems but jsut seems to work around it.
If I call the replacemente in decreasing order that problem just does not show up becouse condition of replacement involving higher numbers are matched before the smaller one.
but should some one suggest a complete "true code comply" solution is wellcome
I am working on a project where I require to format incoming numbers in the following way:
###.###
However I noticed some results I didn't expect.
The following works in the sense that I don't get an error:
console.log(07);
// or in my case:
console.log(007);
Of course, it will not retain the '00' in the value itself, since that value is effectively 7.
The same goes for the following:
console.log(7.0);
// or in my case:
console.log(7.000);
JavaScript understands what I am doing, but in the end the actual value will be 7, which can be proven with the following:
const leadingValue = 007;
const trailingValue = 7.00;
console.log(leadingValue, trailingValue); // both are exactly 7
But what I find curious is the following: the moment I combine these two I get a syntax error:
// but not this:
console.log(007.000);
1) Can someone explain why this isn't working?
I'm trying to find a solution to store numbers/floats with the exact precision without using string.
2) Is there any way in JS/NodeJS or even TypeScript to do this without using strings?
What I currently want to do is to receive the input, scan for the format and store that as a separate property and then parse the incoming value since parseInt('007.000') does work. And when the user wants to get this value return it back to the user... in a string.. unfortunately.
1) 007.000 is a syntax error because 007 is an octal integer literal, to which you're then appending a floating point part. (Try console.log(010). This prints 8.)
2) Here's how you can achieve your formatting using Intl.NumberFormat...
var myformat = new Intl.NumberFormat('en-US', {
minimumIntegerDigits: 3,
minimumFractionDigits: 3
});
console.log(myformat.format(7)); // prints 007.000
Hi
You can use an aproach that uses string funtions .split .padStart and .padEnd
Search on MDN
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padEnd
Here you have an example:
const x = 12.1;
function formatNumber( unformatedNumber) {
const desiredDecimalPad = 3;
const desiredNonDecimalPad = 3;
const unformatedNumberString = unformatedNumber.toString();
const unformatedNumberArr = unformatedNumberString.split('.');
const decimalStartPadded = unformatedNumberArr[0].padStart(desiredDecimalPad, '0');
const nonDecimalEndPadded = unformatedNumberArr[1].padEnd(desiredNonDecimalPad, '0');
const formatedNumberString = decimalStartPadded + '.' + nonDecimalEndPadded;
return formatedNumberString;
}
console.log(formatNumber(x))