How to subtract from a number contained in a string? - javascript

I have a string that contains a number, eg,
images/cerberus5
The desired result
images/cerberus4
How can I subtract 1 from the '5' in the first string to obtain the '4' in the second?

This is a raw example, but you could do something like this:
$old_var = 'images/cerberus4';
$matches = [];
$success = preg_match_all('/^([^\d]+)(\d+)$/', $old_var, $matches);
$new_val = '';
if (isset($matches[2]) && $success) {
$new_val = $matches[2][0].((int)$matches[2][0] + 1);
}
It's not meant to be the perfect solution, but just to give a direction of a possible option.
What the RegEx doesn't detect (because it's more strict) is that it won't work without a trailing number (like images/cerberus), but as it seems an 'expected' pattern I also wouldn't allow the RegEx to be more loose.
By putting this code into a function or class-method you could add a parameter to automatically be able to tell the code to add, subtract or do other modifications to the trailing number.

function addOne(string){
//- Get first digit and then store it as a variable
var num = string.match(/\d+/)[0];
//- Return the string after removing the digits and append the incremented ones on the end
return (string.replace(/\d+/g,'')) + (++num);
}
function subOne(string){
var num = string.match(/\d+/)[0];
//- Same here just decrementing it
return (string.replace(/\d+/g,'')) + (--num);
}
Don't know if this is good enough but this is just two functions that return the string. If this has to be done via JavaScript so doing:
var test = addOne("images/cerberus5");
Will return images/cerberus6
and
var test = subOne("images/cerberus5");
Will return images/cerberus4

Related

How to create a code where an integer is converted to three digets and added to a string

I want to create a code where an integer is converted to three digits and added to a string.
Something like this:
let
value = String. Format("tstexa%03d",Script.Index);
return value;
Where Script. Index is an integer.
I belive you want the final answer to be "tstexa045" when example Script.Index value is 45
let paddedString = Script.Index.toString().padStart(3, '0'); //045
let value = "tstexa" + paddedString;
console.log(value); // example tstexa045

Javascript slicing with 3 parameters

I am attempting to slice my text, in such a way that if the character lenght of a text exceeds the given value, the text should slice from 0 to the value + also go until the next dot is found, so that we avoid slicing a text midsentence.
I've attempted the following
function shorten(text, num)
{
var fulltext=text.toString();
var firstdot = fulltext.indexOf(".");
if (fulltext.length < num)
{
return fulltext;
}
else
{
return fulltext.slice(0, (num + fulltext.indexOf(".")));
}
}
So the logic is, if the text is below the given value, full text is returned, if not i want to slice the text, but also include the text, until next dot.
So once the num value has been reached in characters, it should keep searching until it finds the next dot, and then stop.
Example of what i want given lets say 10 as the num value.
"Hello. This is a test example. This part should be removed."
Should return: "Hello. This is a test example." but instead it will return "Hello. This"
var str = "Hello. This is a test example. This part should be removed."
function shorten(text,num){
let dot = text.indexOf(".",num),
end = dot>=0?dot+1:num
return text.slice(0,end)
}
console.log(shorten(str,6))
some definition
lets say limit num is = 10
indexOf(".",num) since i am taking 10 letters without caring about dot so i have started checking for . after 10 letters that is what second parameter is doing here
dot>=0?dot+1:num this is a short hand which checking if dot is greater than or equals to 0 if its true then return value of dot otherwise return num value
(dot+1) +1 is used to take last dot when slicing without this result will have no dot at end
Please change some code like this
function shorten(text, num)
{
const fulltext=text.toString();
const firstdot = fulltext.indexOf(".", num);
return fulltext.length < num ? fulltext : fulltext.slice(0, firstdot + 1);
}
console.log(shorten("Hello. This is a test example. This part should be removed.", 10));

continually add values in javascript with while loop

I'm a newbie to Javascript so please bear with me for this basic question,
I'm trying to get my function to add all the individual digits in a string together, and then keep doing this until I'm left with a single digit!
3253611569939992595156
113 // result of the above digits all added together
5 //result of 1+1+3
I've created a while loop, but it only adds the numbers together once, it dosn't repeat until a single digit and I can't work out why!
function rootFunc(n) {
var splite = n.toString().split('').map(x => Number(x)); //converts the number to a string, splits it and then converts the values back to a number
while (splite.length > 1) {
splite = splite.reduce(getSum);
}
return splite;
}
console.log(rootFunc(325361156993999259515));
function getSum(total, num) {
return total + num;
}
You're reducing properly, but what you're not doing is re-splitting. Try breaking this out into separate functions:
function digits(n) {
return n.toString().split('').map(x =>Number(x));
}
Then split each time:
function rootFunc(n) {
var d = digits(n);
while (d.length > 1) {
d = digits(d.reduce(getSum));
}
return d;
}
The problem here is that you return the result after the first splice. You need to have a recursive function. To do this, you can put this before the return :
if(splite > 9) splite = rootFunc(splite);
This way, you check if the result is greater than 10, if not you do the function with the remaining digits
I was looking this over in jsfiddle, and your number isn't being passed to exact precision, so just console logging n as soon as you call rootFunc, you've already lost data. Otherwise, to fix your loop, you need to remap splite to a string before the end of your codeblock since your while statement is checking .length, which needs to be called on a string. Put this piece of code at the end of the block:
splite = splite.toString().split('').map(x =>Number(x));

Devide numbers on countup function

I'm starting to learn javascript and I basically needed a countup that adds an x value to a number(which is 0) every 1 second. I adapted a few codes I found on the web and came up with this:
var d=0;
var delay=1000;
var y=750;
function countup() {
document.getElementById('burgers').firstChild.nodeValue=y+d;
d+=y;
setTimeout(function(){countup()},delay);
}
if(window.addEventListener){
window.addEventListener('load',countup,false);
}
else {
if(window.attachEvent){
window.attachEvent('onload',countup);
}
}
There's probably residual code there but it works as intended.
Now my next step was to divide the resultant string every 3 digits using a "," - basically 1050503 would become 1,050,503.
This is what I found and adapted from my research:
"number".match(/.{1,3}(?=(.{3})+(?!.))|.{1,3}$/g).join(",");
I just can't find a way to incorporate this code into the other. What should I use to replace the "number" part of this code?
The answer might be obvious but I've tried everything I knew without sucess.
Thanks in advance!
To use your match statement, you need to convert your number to a String.
Let's say you have 1234567.
var a = 1234567;
a = a + ""; //converts to string
alert(a.match(/.{1,3}(?=(.{3})+(?!.))|.{1,3}$/g).join(","));
If you wish, you can wrap this into a function:
function baz(a) {
a = a + "";
return a.match(/.{1,3}(?=(.{3})+(?!.))|.{1,3}$/g).join(",");
}
Usage is baz(1234); and will return a string for y our.
While I do commend you for using a pattern matching algorithm, this would probably be easier to, practically speaking, implement using a basic string parsing function, as it doesn't look anywhere as intimidating from just looking at the match statement.
function foo(bar) {
charbar = (""+bar).split(""); //convert to a String
output = "";
for(x = 0; x < charbar.length; x++) { //work backwards from end of string
i = charbar.length - 1 - x; //our index
output = charbar[i] + output; //pre-pend the character to the output
if(x%3 == 2 && i > 0) { //every 3rd, we stick in a comma, except if it is not the leftmost digit
output = ',' + output;
}
}
return output;
}
Usage is basically foo(1234); which yields 1,234.

Round the value in Javascript

I have scenario where if user enters for example 000.03, I want to show the user it as .03 instead of 000.03. How can I do this with Javascript?
You can use a regular expression:
"000.03".replace(/^0+\./, ".");
Adjust it to your liking.
This actually is trickier than it first seems. Removing leading zero's is not something that is standard Javascript. I found this elegant solution online and edited it a bit.
function removeLeadingZeros(strNumber)
{
while (strNumber.substr(0,1) == '0' && strNumber.length>1)
{
strNumber = strNumber.substr(1);
}
return strNumber;
}
userInput = "000.03";
alert(removeLeadingZeros(userInput));
How about:
function showRounded(val) {
var zero = parseInt(val.split('.')[0],10) === 0;
return zero ? val.substring(val.indexOf('.')) : val.replace(/^0+/,'') );
}
console.log(showRounded('000.03')); //=> ".03"
console.log(showRounded('900.03')); //=> "900.03"
console.log(showRounded('009.03')); //=> "9.03"
Or adjust Álvaro G. Vicario's solution to get rid of leading zero's into:
String(parseFloat("090.03")).replace(/^0+\./, ".")
This function will take any string and try to parse it as a number, then format it the way you described:
function makePretty(userInput) {
var num,
str;
num = parseFloat(userInput); // e.g. 0.03
str = userInput.toString();
if (!isNaN(num) && str.substring(0, 1) === '0') {
str = str.substring(1); // e.g. .03
} else if (isNaN(num)) {
str = userInput; // it’s not a number, so just return the input
}
return str;
}
makePretty('000.03'); // '.03'
makePretty('020.03'); // '20.03'
It you feed it something it cannot parse as a number, it will just return it back.
Update: Oh, I see If the single leading zero needs to be removed as well. Updated the code.
Assuming your input's all the same format, and you want to display the .
user = "000.03";
user = user.substring(3);
You can convert a string into a number and back into a string to format it as "0.03":
var input = "000.03";
var output = (+input).toString(); // "0.03"
To get rid of any leading zeroes (e.g. ".03"), you can do:
var input = "000.03";
var output = input.substr(input.indexOf(".")); // ".03"
However, this improperly strips "20.30" to ".30". You can combine the first two methods to get around this:
var input = "000.03";
var output = Math.abs(+input) < 1 ?
input.substr(input.indexOf(".")) :
(+"000.03").toString();

Categories