Check in JavaScript if String has x number string

3

Hello, I'd like to know if you have any way to check if a String has JavaScript in it, for example, random number to trigger an event. Here's how:

  

abc123de45

It should be false

  

abc13525de

It should be true

  

ab12cde453fgh76i8jk9

It should be false

Thank you!

    
asked by anonymous 03.02.2017 / 15:45

3 answers

4

You can use it with match

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

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

You can use a function that assembles the string and uses .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));
    
03.02.2017 / 15:54
0

According to this gringo OS answer :

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

2) (ES6) includes - use if you have ES6

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

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

    
03.02.2017 / 15:51