Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I see questions asked on truncating the leading zeros, but nothing found to solve my issue. I have a array of strings representing days returning from an api call.
Ex:
arr= ["061-094", "0561-0960", "000-005", "180+"];
arr.map(function(d){
<div>{d} days</div> // this returns 061-094 days
});
1) How can I remove the leading zeros so that it displays like:
61-94 days
561-960 days
0-5 days
2) How can display:
more than 180 days
for "180+" value?
Thanks
You can use map to generate a new array by testing each value, and if it matches the nn-nn pattern, split the string into numbers, convert to number (removes leading zeros but keeps "0" as a single value), then put them back as strings.
If the string matches the nn+ pattern, process it accordingly.
E.g.
var arr = ["061-094", "0561-0960", "000-005", "180+"];
var result = arr.map(function(v) {
// deal with nn-nn
if (/\d+-\d+/.test(v)) {
return v.split('-').map(s => +s).join('-');
}
// Deal with nn+
if (/\d+\+/.test(v)) {
return v.replace(/(\d+).*/, 'more than $1 days');
}
});
console.log(result);
If you want to wrap in HTML, then do that too.
Assuming there's no other patterns in your data than 000-000 or 180+:
arr = ["061-094", "0561-0960", "000-005", "180+", "90+"];
var result = arr.map(function(d){
if (d.substr(-1) == "+") {
return "<div>More than " + d.slice(0,-1) + " days</div>";
}
var parts = d.split("-");
var truncatedParts = [];
parts.map(function(part) {
truncatedParts.push(parseInt(part, 10));
});
return "<div>" + truncatedParts.join("-") + " days</div>" ;
});
console.log(result);
Have you tired making a String to remove all leading zeros?
String strPattern = "^0+";
This should remove all leading zeros but not trailing zeros.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have the time of day in strings ie. (830, 1450, 1630). I know I can do simple if statements to check if the length is 3 or 4 and get out (8) and (30) or (14) and (50), but is there a cleaner way to split the hour and the minute without having to check in if statements?
There's a simple way with Regular Expressions, though the syntax looks a little weird.
/^(\d{1,2})(\d{2})$/
/ / starts/stops regex definition
^ matches from the start of the string (not a random middle location)
( )( ) match two groups
\d a digit...
{1,2} that needs to exist 1 or 2 times
\d a digit...
{2} that needs to exist two times
Used in code, it would look something like this:
const times = ["830", "1520", "1015"];
const regex = /^(\d{1,2})(\d{2})$/;
const extractTime = (s) => s.match(regex).slice(1, 3);
times.map(extractTime).forEach(([hours, minutes]) => console.log({
hours,
minutes
}))
String.prototype.slice offers an easy way to do this, because negative numbers are interpreted as from the end of the string.
minutes = s.slice(-2) // last two characters of s
hours = s.slice(0, -2) // from first character up to but not including last two characters
If you know that your time will always be represented in HH:mm, you can pad the string and then slice the parts.
const parseTime = (time: string): [string, string] => {
const timePadded = time.padStart(4, 0)
return [timePadded.slice(0, 2), timePadded.slice(2, 4)]
}
parseTime("830") # ["08", "30"]
parseTime("1430") # ["14", "30"]
const a = [830, 1450, 1630];
a.forEach((item) => {
console.log('Hour = ' + ('0' + item).slice(-4).substring(0, 2) + ' Minute = ' + item.toString().slice(-2));
});
a.forEach((item) => {
console.log('Hour = ' + ('0' + item).slice(-4, -2) + ' Minute = ' + item.toString().slice(-2));
});
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I need to replace 02:04.887004 to 02:04.887 with jquery or js.
Other times I have microseconds just with four decimals (02:04.8348) and I would have 02:04.834
I would use regexp to find $:[d][d].$ and then return it but with the three decimals
If the length of the string is reliable, you can just trim the unwanted characters from the string, e.g.
let time = '02:04.887004';
// If format is reliable, get first 9 characters
console.log(time.substr(0,9));
// If length might vary and number of decimals is at least 3
// Trim from end
console.log(time.slice(0, -(time.length - time.indexOf('.') - 4)))
// Trim from start
console.log(time.substr(0, time.length - time.indexOf('.') + 2));
If the format is more unreliable, you have more work to do.
You can use a regular expression or a split function or a substring on the string to format your timestring. Here is an example of the three:
const time = '02:04.887004';
const regex = /[\d]{2}:[\d]{2}\.[\d]{3}/
const formatTime = time => {
const match = time.match(regex);
return match ? match[0] : match;
}
const formatTime2 = time => {
const m = time.split(':').shift();
const s = time.split(':').pop().split('.').shift();
const ms = time.split('.').pop().substr(0,3);
return m + ':' + s + '.' + ms;
}
const formatTime3 = time => {
return time.substr(0,9);
}
console.log(formatTime(time));
console.log(formatTime2(time));
console.log(formatTime3(time));
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I am trying to write a program to decrypt a encrypted message. The encrypted message is a very long set of numbers ".296.294.255.268.313.278.311.270.290.305.322.252.276.286.301.305.264.301.251.269.274.311.304.
230.280.264.327.301.301.265.287.285.306.265.282.319.235.262.278.249.239.284.237.249.289.250.
282.240.256.287.303.310.314.242.302.289.268.315.264.293.261.298.310.242.253.299.278.272.333.
272.295.306.276.317.286.250.272.272.274.282.308.262.285.326.321.285.270.270.241.283.305.319.
246.263.311.299.295.315.263.304.279.286.286.299.282.285.289.298.277.292.296.282.267.245.....ect".
Each character of the message is transformed into three different numbers (eg.first character of message is '230 .280 .264' second character is '.327.301.265' ect).
so i am trying to use javascript to add the groups of three numbers and then save them as their own variable. thanks
Assuming msg has that string in it, this will split it up and add the triplets together.
const [, triplets] = msg
.split('.')
.slice(1)
.map(v => +v)
.reduce(([count, list], val, i) => {
if ((i + 1) % 3) return [count + val, list];
return [val, list.concat(count)];
}, [0, []]);
It would depend on how the data is transmitted. It looks like you could bring the data in as a string (or parse it into a string) and then use the split method to create an array of all of your numbers.
var numbers = "234.345.456.567"
var arr = numbers.split(".")
You would then loop over the array doing whatever you need for every set of three
var newArray[]
var i
for(i = 0; i < length; i += 3){
//Add values here
//Parse back to int
newArray.push("sum Value")
}
Hope this was along the lines of what you need.
Use a regular expression to match all groups of three, then map each group to the number by splitting the string by .s and adding the 3 together:
const input = '296.294.255.268.313.278.311.270.290.305.322.252.276.286.301.305.264.301.251.269.274.311.304. 230.280.264.327.301.301.265.287.285.306.265.282.319.235.262.278.249.239.284.237.249.289.250. 282.240.256.287.303.310.314.242.302.289.268.315.264.293.261.298.310.242.253.299.278.272.333. 272.295.306.276.317.286.250.272.272.274.282.308.262.285.326.321.285.270.270.241.283.305.319. 246.263.311.299.295.315.263.304.279.286.286.299.282.285.289.298.277.292.296.282.267.245';
const groupsOfThree = input.match(/\d{3}\.\d{3}\.\d{3}\./g);
const sums = groupsOfThree.map((group) => {
const nums = group.split('.').map(Number);
return nums[0] + nums[1] + nums[2];
});
console.log(sums);
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have an string of numbers "123456" i want to split them in all possible ways.
So
1 23456
1 2 3456
1 23 45 6
1234 5 6
and so on
What i have tried...
looping over len-1, and splitting on every index, but logically it misses a lot of possible scenarios.
You could try a recursive function like below...
<script lang="javascript">
// Split string into all combinations possible
function splitAllWays(result, left, right){
// Push current left + right to the result list
result.push(left.concat(right));
//document.write(left.concat(right) + '<br />');
// If we still have chars to work with in the right side then keep splitting
if (right.length > 1){
// For each combination left/right split call splitAllWays()
for(var i = 1; i < right.length; i++){
splitAllWays(result, left.concat(right.substring(0, i)), right.substring(i));
}
}
// Return result
return result;
};
var str = "123456";
var ans = splitAllWays([], [], str);
</script>
Results
123456
1,23456
1,2,3456
1,2,3,456
1,2,3,4,56
1,2,3,4,5,6
1,2,3,45,6
1,2,34,56
1,2,34,5,6
1,2,345,6
1,23,456
1,23,4,56
1,23,4,5,6
1,23,45,6
1,234,56
1,234,5,6
1,2345,6
12,3456
12,3,456
12,3,4,56
12,3,4,5,6
12,3,45,6
12,34,56
12,34,5,6
12,345,6
123,456
123,4,56
123,4,5,6
123,45,6
1234,56
1234,5,6
12345,6
I think that is the right results (32 combinations). Can someone confirm?
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have an expression such as xsin(x) it is valid only if * comes between x and sin(x) and make it as x*sin(x)
my idea is first search for x then insert * between x and another variable if there is a variable.
equation
sin(x)cos(x) to sin(x)*cos(x)
pow((x),(2))sin(x)to pow((x),(2))*sin(x)
sin(x)cos(x)tan(x) to sin(x)*cos(x)*tan(x)
etc
I am trying with this code..
function cal(str)
{
//var string = "3*x+56";
var regex = /([a-z]+)\(\(([a-z]+)\),\(([0-9]+)\)\)\(([a-z0-9\*\+]+)\)([\*\-%\/+]*)/;
var replacement = "$1($2($4),($3))$5";
while(str.match(regex))
{
str = str.replace(regex,replacement);
}
return str;
}
This one matches right parentheses followed by a letter (e.g. )s ), and inserts a * (e.g. )*s )
It also replaces x followed by a letter with x* and that letter
It should work for x+sin(x) and xsin(x)
function addStars(str) {
return str.replace(/(\))([A-Za-z])/g,function(str, gr1, gr2) { return gr1 + "*" + gr2 }).replace(/x([A-Za-wy-z])/g,function(str, gr1) { return "x*" + gr1 })
}
document.write(addStars("x+sin(x)tan(x)ln(x)+xsin(x)"))
Help from:
JavaScript - string regex backreferences
qwertymk's answer
> 'sin(x)cos(x)'.replace(/(?!^)\w{3}/g, '*$&')
< "sin(x)*cos(x)"
> 'pow((x),(2))sin(x)'.replace(/(?!^)\w{3}/g, '*$&')
< "pow((x),(2))*sin(x)"
> 'sin(x)cos(x)tan(x)'.replace(/(?!^)\w{3}/g, '*$&')
< "sin(x)*cos(x)*tan(x)"
This says: replace anything that doesn't start at the beginning and has three letters with a * and everything that matched