How to take the first letter inside a String in Javascript if the first character is a number?

0

For example

  

12kghggdhfj74ghg8hgh

From the string I should take the 12 and the k but the text can change can be

  

127rnbvcx

And from there I should take the 127 and the r and save it in each variable

PD. strings are entered from an input

    
asked by Carlos Carlos 05.10.2017 в 01:17
source

2 answers

0

This is a possible solution that includes the omission of special characters, I assume that, as mentioned in the title of the question, the first characters are numbers

The algorithm consists in iterating over the string of numbers and letters, accumulating digits until finding the first letter, returning an object. To check if a value is numerical, I based myself on what was discussed in the following question: how to check whether a value is a number in javascript or jquery

function isNumeric(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

function processInput(input){
   let result = {
     firstNumber:"",
     firstLetter:""
   }
   const cleanInput = input.replace(/[^\w\s]/gi, ''); // reemplazo todo lo que no sea una letra o un digito. Esto podria no ser necesario si ya se asume que se controla en el ingreso de datos.
   console.log("input: %s, clean input: %s", input, cleanInput);
   for (let i in cleanInput) {
     if(isNumeric(cleanInput[i])){
        result.firstNumber += cleanInput[i];
     }else{
        result.firstLetter = cleanInput[i];
        break;
     }
  } 
  return result;
}


console.log(processInput("123dkkkk"));
console.log(processInput("23dk"));
console.log(processInput("1d23dkkkk"));
console.log(processInput("#11d23dk"));
console.log(processInput("#1..1??#23dk"));
console.log(processInput("#1..1??#DDD23dk"));
    
answered by 05.10.2017 / 01:51
source
0

Another possible solution would be the following one; surely you can do everything with a more complex regular expression (if any crack in regexp knows it, feel free to suggest it).

const getSerie = (str) => {
  if(isNaN(str[0])) { throw new Error('Serie must start with a number'); }
  const matches = str.match(/\d+\.\d+|\d+\b|\d+(?=\w)/);
  const match = matches[0];
  const index = matches.indexOf(match) + match.length;
  const nextChar = str.substr(index, 1);
  const isLetter = /[a-zA-Z]/.test(nextChar);

  if (isLetter) {
    return match + nextChar;
  } else {
    return null;
  }
};

// Ejemplo
const serie1 = getSerie("12rdjdjdf4kgjdg");
const serie2 = getSerie("123fdjdjdf4kgjdg");
const serie3 = getSerie("123$djdjdf4kgjdg");

console.log('Serie:', serie1);
console.log('Serie:', serie2);
console.log('Serie:', serie3);

const serie4 = getSerie("adjdjd5f4kgjdg"); // error

console.log('Serie:', serie4);
    
answered by 05.10.2017 в 02:13