0

Hi i am try to find a variable date in a string with a regex and after this i want to save the date in a new variable my code looks like:

var valide =new RegExp(/\d{2}([./-])\d{2}\1\d{4}$/mg);
var text = 'lalaahfdsdfl 02.02.1989';//example
if(valide.test(text) === true){

}

how can i put the found date (02.02.1989) in a new variable

5 Answers5

0

You can create groups in your Regex expression (just put the values you want between parenthesis) and then use this to get the specific group value.

Note, however, I think your regex is wrong... it seems you end with 1 plus 4 digits

user1156544
  • 1,725
  • 2
  • 25
  • 51
0

You can use match on a string:

var valide =new RegExp(/\d{2}([./-])\d{2}\1\d{4}$/mg);
var text = 'lalaahfdsdfl 02.02.1989';//example

console.dir(text.match(valide)) // ["02.02.1989"]

if(valide.test(text) === true){

}
OliverRadini
  • 6,238
  • 1
  • 21
  • 46
0

You can use match for that:

var valide =new RegExp(/\d{2}([./-])\d{2}\1\d{4}$/mg);
var text = 'lalaahfdsdfl 02.02.1989';//example

var foundDate = text.match(valide);

console.log(foundDate);

Also, you can make the regex a bit simpler if you switch the ([./-]) to ([-.]), because - is considered a literal match if it comes first inside a character class.

Isac
  • 1,834
  • 3
  • 17
  • 24
0

Using REGEXP function match you can extract the part that match your regular expression.

After this you will get an object. In this case i turn it into a string so you can do a lot more things with it.

var myDate = text.match(valide).toString();

Hope this helps :>

var valide =new RegExp(/\d{2}([./-])\d{2}\1\d{4}$/mg);
var text = 'lalaahfdsdfl 02.02.1989';//example

if(valide.test(text) === true){
var myDate = text.match(valide).toString();
console.log(myDate)
}
Gerardo BLANCO
  • 5,590
  • 1
  • 16
  • 35
0

You could do something like this.
var result = text.match(valide)

Here is a reference for the match method String.prototype.match

James Harrington
  • 3,138
  • 30
  • 32
Raylian
  • 163
  • 4
  • While this may answer the question it's better to include some description on how this answer help to solve the issue. Please read [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer). – Narendra Jadhav Jun 07 '18 at 13:22