-2

String is Dynamic.Example

Date18:Month5:Year1984

How can we extract just number 18. I cannot use substring because the values are dynamic.I want to extract only the number after Date and before :

BTVS
  • 21
  • 4

2 Answers2

0

Here is what you want:

const a = "Date18:Month5:Year1984";
const match = a.match(/^Date([0-9]+?):/);

if(match){
  console.log(match[1]);
}
8HoLoN
  • 1,122
  • 5
  • 14
  • It resolved my issue.I am not familiar with Regular expressions.It really saved my time.Thank you! – BTVS Jul 22 '20 at 14:04
0

regular expressions are great for matching patterns. There are many ways you can write it, here is a couple ways.

var str = "Date18:Month5:Year1984"

const re = /^Date(\d+):Month(\d+):Year(\d+)$/;

const match = str.match(re);

console.log(match[1], match[2], match[3]);


const re2 = /(\d+)/g;

const match2 = str.match(re2);

console.log(match2[0], match2[1], match2[2]);
epascarello
  • 204,599
  • 20
  • 195
  • 236