Check in Javascript if String has string x numbers

Asked

Viewed 793 times

3

Hello, I wonder if there is any way to check if a String has Javascript, for example, 5 number in a random sequence to trigger an event. Therefore:

abc123de45

Must be false

abc13525de

Must be true

ab12cde453fgh76i8jk9

Must be false

Thank you!

  • Your sequence will be fixed or variable?

  • I take the value of a textarea field in a form and with each letter typed the variable changes: $(Document). on('input', '#content', Function(){ var content = $('#content'). val(); }

  • The question @Sorack raised is about the sequence: want to validate only 12345, or worth any sequence? Type 23456, 56789, 89012 (will be circular?).

  • 1

    ops, sorry. Serves any sequence of X numbers.

  • Should the numbers be sorted? Or a sequence of five numbers, sorted or not? Ex: ac12458cd

  • can be a random sequence, the important thing is to be 5 numbers in a row, I’ve edited the question.

Show 1 more comment

3 answers

4


Can use with match

var str0 = 'abc123de45'
console.log((str0.match(/[0-9]{5}/) != null));

var str1 = 'abc12345de';
console.log((str1.match(/[0-9]{5}/) != null));

  • 1

    Good solution using regex

  • 1

    worked perfectly!

1

You can use a function that mounts the sequence and use .indexOf to check it:

function verificarSequencia(texto, quantidade) {
  var regex = new RegExp('\\d{' + quantidade + '}', 'g');

  return regex.test(texto);
}

console.log('abc123de45', verificarSequencia('abc123de45', 5));
console.log('abc12345de', verificarSequencia('abc12345de', 5));
console.log('ab12cde345fgh67i8jk9', verificarSequencia('ab12cde345fgh67i8jk9', 5));

  • 1

    +1 good .........

0

According to this reply of the Gringo SO:

1) index - to see if the string has the other string, it will return -1 if it does not have

2) (ES6) includes - use if using ES6

var string = "foo",
substring = "oo";
string.includes(substring);

I think these are the easiest, I’m leaving home but then edit with all of the answer ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.