randyHurd
randyHurd

Reputation: 64

Getting a number from a string

I have a string with a number on the end, "slot1" and would like to get the number from it.

currentSlot.name = "slot1";
slotNumber =  currentSlot.name - "slot"; // I want it to be 1

Upvotes: 1

Views: 374

Answers (2)

gabriel
gabriel

Reputation: 2359

I had similar needs in previous projects and decided to use RegExp, so, doesn't matter the string format, always will extract the number (if possible).

var n:Number = getNumbersFromString("slot1"); // can be 1slot, s1lot, etc) always will return 1

trace(n, n is Number);

function getNumbersFromString(source:String):Number
{
    var pattern:RegExp = /[^0-9]/g;
    return Number(source.replace(pattern, ''));
}

Upvotes: 1

Dyrandz Famador
Dyrandz Famador

Reputation: 4525

since you want a number then you probably need to convert it.

you will need substr() to get the number and Number() to convert it to number.

You can convert strings that are made up of numerical characters into actual Number data using the Number()

currentSlot.name = "slot1";
slotNumber =  Number(currentSlot.name.substr(4));

Number() constructor expects a number, so don't put a calculation inside

Upvotes: 1

Related Questions