Home > database >  javascript : get numbers after entry in string
javascript : get numbers after entry in string

Time:10-10

I have a text and I want to search in text, find the word ,and then return the numbers after this word

for example :

this is a signal , entry : 2430 and side is short

I want to find entry and return 2430

how can I handle this?

CodePudding user response:

You can use indexOf to find (the place of) the word and match (the numbers after this word) methods for Strings to achieve this.

Below is an example to achieve your goal; however, if you are not familiar with Regex, I suggest you learn more about it.

const myString = "this is a signal , entry : 2430 and side is short";
const wordStartingIndex = myString.indexOf('entry :'); // this will give you the index of your word.
const index = wordStartingIndex   7; // since your word string has 7 characters.
const slicedString = myString.slice(index); // gives you the string part after the "word";
const numberMatch = slicedString.match(/\d /); // gives you the first match.

Since you are asking for "the numbers", you can use /\d /g regex for your match. g tag will look for globally in your string and will give you an array of matches.

CodePudding user response:

You can also do with indexOf and regular expression

const word = "entry";
const str = "this is a signal , entry : 2430 and side is short";

const index = str.indexOf(word);

if (index !== -1) {
  let result = str.slice(index   word.length).match(/\d /)[0];
  console.log(result);
}

CodePudding user response:

Just use a simple regex:

const input = 'this is a signal , entry : 2430 and side is short'; 

const number1 = input.match(/entry\W (\d )/)?.[1]; // "2430"

const number2 = input.match(/santa\W (\d )/)?.[1]; // undefined

CodePudding user response:

If you want it on 1 line:

text = 'this is a signal , entry : 2430 and side is short';
x = text.split('entry : ')[1].split(' ')[0];
  • Related