Nakul Tiruviluamala
Nakul Tiruviluamala

Reputation: 565

Trying to extract the substring of a string until the string's first number

I am trying to extract the substring of a string until the string's first number.

var notes = ["D4", "F#8", "Abb2"];
note[0].substring(0,notes[0].indexOf(4);

//returns D, gets rid of 1

However, this only works if the first number is 4. Other items in my notes array have numbers that are different.

I've tried to modify my code so that the argument for indexOf is a regular expression, but it isn't working:

var reg = /^\d+$/;
notes[0].substring(0,notes[0].indexOf(reg));

Thank you.

Upvotes: 2

Views: 744

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386550

You could get the first part without number.

function getNote(string) {
    return string.match(/^\D+/)[0];
}

var notes = ["D4", "F#8", "Abb2"];

console.log(notes.map(getNote));

Upvotes: 3

Related Questions