So I have this code that would get the first string's from the right hand side and stop whenever there is an integer but for some reason its not working with me.
Example input of fUnit is "CS_25x2u"
expected output of it after using unit is "u".
Real output is "undefined".
function buildUnit(fUnit){// wahts ginna be passed here is the gibirish unit and the output of this function is the clear unit
fUnit = fUnit.toString;
const regex = /[a-zA-Z]*$/;
const unit = (x) => x.match(regex)[0];
fUnit = unit(fUnit);
If you need more info please let me know
Thank you
const regex = /[a-zA-Z]*$/;
console.log(regex.exec(sample));
Assuming fUnit variable contains your string
const unit = (x) => x.match(regex)[0];
console.log(unit(fUnit));
Just in case.
function buildUnit(fUnit) {
return fUnit.toString().match(/[A-z]*$/)[0];
}
console.log(buildUnit('CS_25x2u')); // 'u'
console.log(buildUnit('')); // ''
console.log(buildUnit(123)); // ''
console.log(buildUnit('aaa123')); // ''
console.log(buildUnit('aaa 123 bbb')); // 'bbb'
Related
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))
I am having some issues solving this problem, and would appreciate if someone could provide guidance on the best way to go about solving it. Thank You.
Write a function onlyLetters that takes a string and returns a new string with the numbers filtered out.
Examples:
onlyLetters('12ab') // => 'ab'
onlyLetters('1xz015')// => 'xz'
onlyLetters('1aasf123ql') // => 'aasfql'
Here is what I wrote:
function onlyLetters(str) {
if(str === isNaN === true) {
return str;
}
}
onlyLetters('12ab');
function onlyLetters(input) {
/*
*Check for characters 0->9 globally in a regex check
*and replace them to '' or nothing.
*/
return input.replace(/[0-9]/g, '');
}
/*
* Single line solution (if necessary)
* let onlyLetters = (input) => input.replace(/[0-9]/g, '');
*/
console.log(onlyLetters('12ab')); // => 'ab'
console.log(onlyLetters('1xz015')); // => 'xz'
console.log(onlyLetters('1aasf123ql')); // => 'aasfql'
How about something as simple as replace? It may be too simple and for that maybe ask another question?
I have the following problem statement:
Write a function, uncompress, that takes in a string as an argument.
The input string will be formatted into multiple groups according to
the following pattern:
number + char
for example, '2c' or '3a'.
The function should return an uncompressed version of the string where
each 'char' of a group is repeated 'number' times consecutively. You
may assume that the input string is well-formed according to the
previously mentioned pattern.
test_00: uncompress("2c3a1t"); // -> 'ccaaat'
Here is my code which is using a stack. The problem is that it's only returning 'cc' and I can't figure out why. I've console logged what goes into the IF ELSE and I'm hitting both so I don't understand why nothing gets pushed to the stack.
Would really appreciate the help if someone can spot what I'm missing.
const uncompress = (s) => {
const nums = '23456789';
const stack = [];
for (let char of s) {
if (nums.includes(char)) {
stack.push(Number(char));
} else {
const num = stack.pop();
stack.push(char.repeat(num));
};
};
return stack.join('');
};
console.log(uncompress("2c3a1t")); // -> 'ccaaat'
Here's how I would do it:
Split the string up into pairs of numbers and chars:
str.match(/\d+[a-zA-Z]/g)
And reduce that array to a string, while taking each value from the array, getting the char from it (cv.match(/[a-zA-Z]/)[0]) and repeating it according to the number (.repeat(parseInt(cv)))
const uncompress = str => str.match(/\d+[a-zA-Z]/g).reduce((acc, cv) =>
acc + cv.match(/[a-zA-Z]/)[0].repeat(parseInt(cv)), "")
console.log(uncompress("2c3a1t"))
console.log(uncompress("27b1d8g"))
And just like that I was able to write the code which passed the test case:
const nums = '123456789';
const stack = [];
for (let char of s) {
if (nums.includes(char)) {
stack.push(Number(char));
} else {
let num = '';
while (nums.includes(stack[stack.length - 1])) {
num += stack.pop();
}
stack.push(char.repeat(num));
};
};
return stack.join('');
};
The initial string:
initString = '/digital/collection/music/bunch/of/other/stuff'
What I want: music
Specifically, I want any term (will never include slashes) that would come between collection/ and /bunch
How I'm going about it:
if(initString.includes('/digital/collection/')){
let slicedString = initString.slice(19); //results in 'music/bunch/of/other/stuff'
let indexOfSlash = slicedString.indexOf('/'); //results, in this case, to 5
let desiredString = slicedString.slice(0, indexOfSlash); //results in 'music'
}
Question:
How the heck do I accomplish this in javascript in a more elegant way?
I looked for something like an endIndexOf() that would replace my hardcoded .slice(19)
lastIndexOf() isn't what I'm looking for, because I want the index at the end of the first instance of my substring /digital/collection/
I'm looking to keep the number of lines down, and I couldn't find anything like a .getStringBetween('beginCutoff, endCutoff')
Thank you in advance!
your title says "index" but your example shows you wanting to return a string. If, in fact, you are wanting to return the string, try this:
if(initString.includes('/digital/collection/')) {
var components = initString.split('/');
return components[3];
}
If the path is always the same, and the field you want is the after the third /, then you can use split.
var initString = '/digital/collection/music/bunch/of/other/stuff';
var collection = initString.split("/")[2]; // third index
In the real world, you will want to check if the index exists first before using it.
var collections = initString.split("/");
var collection = "";
if (collections.length > 2) {
collection = collections[2];
}
You can use const desiredString = initString.slice(19, 24); if its always music you are looking for.
If you need to find the next path param that comes after '/digital/collection/' regardless where '/digital/collection/' lies in the path
first use split to get an path array
then use find to return the element whose 2 prior elements are digital and collection respectively
const initString = '/digital/collection/music/bunch/of/other/stuff'
const pathArray = initString.split('/')
const path = pathArray.length >= 3
? pathArray.find((elm, index)=> pathArray[index-2] === 'digital' && pathArray[index-1] === 'collection')
: 'path is too short'
console.log(path)
Think about this logically: the "end index" is just the "start index" plus the length of the substring, right? So... do that :)
const sub = '/digital/collection/';
const startIndex = initString.indexOf(sub);
if (startIndex >= 0) {
let desiredString = initString.substring(startIndex + sub.length);
}
That'll give you from the end of the substring to the end of the full string; you can always split at / and take index 0 to get just the first directory name form what remains.
You can also use regular expression for the purpose.
const initString = '/digital/collection/music/bunch/of/other/stuff';
const result = initString.match(/\/digital\/collection\/([a-zA-Z]+)\//)[1];
console.log(result);
The console output is:
music
If you know the initial string, and you have the part before the string you seek, then the following snippet returns you the string you seek. You need not calculate indices, or anything like that.
// getting the last index of searchString
// we should get: music
const initString = '/digital/collection/music/bunch/of/other/stuff'
const firstPart = '/digital/collection/'
const lastIndexOf = (s1, s2) => {
return s1.replace(s2, '').split('/')[0]
}
console.log(lastIndexOf(initString, firstPart))
Could someone explain to me, how I can do in javascript this simple code, without taking care of upper and lower case?
if(res.search('em')!=-1){ unit='em'; res.replace(unit,'');}
if(res.search('vh')!=-1){ unit='vh'; res.replace(unit,'');}
if(res.search('px')!=-1){ unit='px'; res.replace(unit,'');}
Without any idea, that is what I have coded. It's a lot of code
if(res.search('Em')!=-1){ unit='Em'; res.replace(unit,'');}
if(res.search('eM')!=-1){ unit='eM'; res.replace(unit,'');}
if(res.search('EM')!=-1){ unit='EM'; res.replace(unit,'');}
...
I'm sure there is a better way to do that!?
Thanks a lot.
You could use a regular expression with replace and save the found unit as a side effect of the replacer function. This would allow you to replace the unit without searching the string twice:
let res = "Value of 200Em etc."
let unit
let newRes = res.replace(/(em|vh|px)/i, (found) => {unit = found.toLowerCase(); return ''})
console.log("replaced:", newRes, "Found Unit:", unit)
For the first part you can use toLowerCase()
if(res.toLowerCase().search('em') != -1)
You can use alternation in regex alongside case insensitive flag.
/(em|vh|px)/i Mathces em or vh or px.
function replaceUnit(input){
return input.replace(/(em|px|vh)/i ,'replaced')
}
console.log(replaceUnit('height: 20em'))
console.log(replaceUnit('width:=20Em'))
console.log(replaceUnit('border-radius: 2Px'))
console.log(replaceUnit('unit=pX'))
console.log(replaceUnit('max-height=20Vh'))
you can use toLowerCase(), transform all the string to lower case and compare,
var tobereplaced = 'em';
if(res.search.toLowerCase(tobereplaced)> -1){ res.replace(tobereplaced,'');}
If you can make these three assumptions:
The string always starts with a number
The string always ends with a unit
The unit is always two characters
Then it could be as simple as:
const str = '11.5px';
const unit = str.substr(-2); //=> 'px'
const value = parseFloat(str, 10); //=> 11.5
Or with a function:
const parse = str => ({unit: str.substr(-2), value: parseFloat(str, 10)});
const {unit, value} = parse('11.5px');
// unit='px', value=11.5
All you need to to is force your string to lowercase (or uppercase) before testing its contents:
if( res.toLowerCase().search('em') !== -1){ do(stuff); }
To handle replacing the actual substring value in res, something like this should work:
let caseInsensitiveUnit = "em";
let unitLength;
let actualUnit;
let position = res.toLowerCase().search(caseInsensitiveUnit);
if(position > -1){
unitLength = caseInsensitiveUnit.length;
actualUnit = res.substring(postion, position + unitLength);
res.replace(actualUnit, "");
}