0

I get an issue using REGEX, it is probably about my REGEX but I need some helps.

I need to match all string containing "D"...

Test string 1 : D
Test string 2 : aaaaaaDqqqqq
Test string 3 : Dssssssss
Test string 4 : D4564646
Test string 5 : 1321313D2312
Test string 6 : ppppprrrrrr

My regex :

/^.+D.+|(:?^|\s)D$/gi

It works only for 1 and 2 and it should works for 1, 2, 3, 4 and 5.

tonymx227
  • 5,293
  • 16
  • 48
  • 91

4 Answers4

0

In your case problem is with + operator which is literally Matches between one and unlimited times so it wont work if letter "D" will be in the beggining or the end of string. Try this regex: ^.*D.*$ with asterix, as it is defined as Matches between zero and unlimited times

See example

Jacek Rosłan
  • 333
  • 4
  • 10
0

Following regex should work for you

.*D.*
Rakesh
  • 4,004
  • 2
  • 19
  • 31
0

If all you need to do is test for whether or not a string contains a D character, it's just /D/

var tests = [
"D",
"aaaaaaDqqqqq",
"Dssssssss",
"D4564646",
"1321313D2312",
"ppppprrrrrr"
]

tests.forEach(str => console.log(/D/.test(str)))
jmcgriz
  • 2,819
  • 1
  • 9
  • 11
-1

Instead of using a regex simply use the includes function

var string = "aaaaaaDqqqqq",
substring = "D";
if(string.includes(substring)){
    console.log("contain")
}else{
    console.log("don't contain")
}
executable
  • 3,365
  • 6
  • 24
  • 52