-1

A few other answers to similar questions mention to simply use an | to do multiple matches, but it doesn't seem to be working in JS for me.

I have the following string: /hi_hawaii_zip_codes_geo.min.json and want to output hawaii.

The following code doesn't work: str.replace(/_z.*|^.{0,5}/, '') however, running _z.*|^.{0,5} matches fine on regexpal.com as a test, and I'm able to replace the correct matching substrings by chaining 2 replace()s.

Is there some special exception for regex in JS or replace that I'm overlooking?

Jacob Simmons
  • 119
  • 1
  • 2
  • 6

2 Answers2

2

Add the global flag:

str.replace(/_z.*|^.{0,5}/g, '')
            add “g” —————-^
Bohemian
  • 412,405
  • 93
  • 575
  • 722
1

It's not clear from the question why replace needs to be used at all. There are at least 2 other approaches to getting "hawaii" from the same str:

str.match(/_(.*?)_/)[1]

and

str.split('_')[1]
cybersam
  • 63,203
  • 6
  • 53
  • 76