iansinnott / react-string-replace

A simple way to safely do string replacement with React components
MIT License
652 stars 56 forks source link

Cannot read property "length" of undefined #74

Closed Kosurij closed 2 years ago

Kosurij commented 2 years ago

If you pass a regExp as second argument in function reactStringReplace you can get error like: Cannot read property "length" of undefined. I think thiss is caused by the work of vanilla replacemethod.

For example, this code give us an error (it's cyrillic): const str = 'Справка Форма Ф9'; const re = /(справка[а-я].?(по)? форм[а-я] [ф|Ф]\d)/gi console.log(str.split(re)); // ["", "Справка Форма Ф9", undefined, ""]

So you cannot get length proprty of undefined. And this error will crush you page. Example_of_undefined

Kosurij commented 2 years ago

My solution - https://github.com/iansinnott/react-string-replace/pull/75

@iansinnott, please check it.

alex-clear commented 2 years ago

Have the same issue with next Regex: /({phone})|({name})/gi Then var result = str.split(re); - provides next result: ['Please enter the code we sent to you at
 ', '{phone}', undefined, '', undefined, '{name}', '. ']

The solution for this can be next fix: var result = str.split(re).filter(Boolean); @iansinnott Can you fix this one?

iansinnott commented 2 years ago

what's the str value?

iansinnott commented 2 years ago

I think your regex is not doing what you expect. try using only one matching group with | to separate alternative matches.

Use https://regex101.com/ for quick iteration testing regex

alex-clear commented 2 years ago

@iansinnott Thanks for remark. You are right, there was an issue with our regex however, IMO, in order to prevent error throws, better to add the solution above(or in existed PR), or to add try catch to the code(maybe return error with 'wrong regex provided' or something similar)

iansinnott commented 2 years ago

Agreed, I pushed a change that should fix this. Thanks for raising the issue. Will publish in next version.