-3

Both giving the same result so what is the difference between "*" and "+" symbol. How would I know which one to use.

var str= "oofo fooloo"
var StarSymbol= str.match(/fo*/g);
var PlusSymbol= str.match(/fo+/g)
console.log(StarSymbol)  // ["fo", "foo"]
console.log(PlusSymbol) // ["fo", "foo"]

fiddle

Jitender
  • 7,593
  • 30
  • 104
  • 210

3 Answers3

1

You are asking the same question again. So let me explain.

var str= "oofo fooloo"
var StarSymbol= str.match(/fo*/g);
var PlusSymbol= str.match(/fo+/g)
console.log(StarSymbol)  // ["fo", "foo"]
console.log(PlusSymbol) // ["fo", "foo"]

Ya, both gives the same result here(for this input) but fo* would match f alone where fo+ would not. * repeats the previous token zero or more times where + repeat the previous token one or more times. So this expects the previous token to be repeated atleast one time.

Example:

> var str= "f"
undefined
> str.match(/fo*/g);
[ 'f' ]
> str.match(/fo+/g);
null
> 
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
  • _"You are asking the same question again"_, so why did you answer? You should've just close-voted it as a duplicate instead. Heck, you have the [tag:regex] mjölnir. – Cerbrus Aug 18 '15 at 06:39
  • 1
    Don't encourage people to just keep posting, by answering them. – Cerbrus Aug 18 '15 at 06:42
0

o* search's for zero or more o's

o+ search's for one or more o's

go through tutorials

Raghavendra
  • 3,530
  • 1
  • 17
  • 18
0

* means between 0 and infinite amount of times, while + means at least one (cannot be zero amount of times)

To be more verbose, * would be like writing {0,}, while + would be like writing {1,}

Moishe Lipsker
  • 2,974
  • 2
  • 21
  • 29