-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?

1

2 Answers 2

2

Add the global flag:

str.replace(/_z.*|^.{0,5}/g, '')
            add “g” —————-^
Sign up to request clarification or add additional context in comments.

1 Comment

thank you! that's what I was missing, didn't realize the particularities of replace().
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]

1 Comment

Thanks! I was aware of split, but really wanted to work and improve my regex through this as well.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.