Extract a string after a javascript delimiter?

Asked

Viewed 121 times

2

I have the following return: 7100-1156 As a result I would like to always extract the second part of the string: 1156.

The example code does this but the problem is when the value of the first part of the string has less or more characters.

The idea is to extract everything you have after the - in any situation.

var codigo =  "7100-1156";
var resultado = codigo.substring(5, 15);

console.log(resultado);

  • Please what would be the other examples, why give a split will not solve in all cases?

2 answers

2


You can do it using the method split(), which basically separates the string by an identifier, in this case the character - in a array then just take the part you want to use:

var codigo =  "7100-1156";
var resultado = codigo.split('-');

console.log(resultado[1]);

  • 1

    Leandrade thank you very much, God bless you!

  • For nothing Andre, amen!!

1

In addition to a split, you could also use a regex to automatically pick up the second part of the string:

'7100-1156'.replace(/(\d{4})-(\d{4})/g, '\$2')

In this code, the string was divided into two groups, one before the hyphen and the other after, each containing 4 digits. No replace, we say to replace the whole expression only by its second group - which corresponds to the desired.

Browser other questions tagged

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