Bandarbola855
Bandarbola855

Reputation: 127

How to subtract from a number contained in a string?

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?

Upvotes: 0

Views: 59

Answers (2)

Razentic
Razentic

Reputation: 26

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

Upvotes: 1

user1467267
user1467267

Reputation:

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.

Upvotes: 2

Related Questions