Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit f4cb7ed

Browse files
Add undefined check. Closes #74
1 parent 47a1b56 commit f4cb7ed

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

‎index.js‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ var flatten = function (array) {
4646
* // => ['Emphasize all phone numbers like ', <strong>884-555-4443</strong>, '.'
4747
*
4848
* @param {string} str
49-
* @param {regexp|str} match Must contain a matching group
49+
* @param {RegExp|str} match Must contain a matching group
5050
* @param {function} fn
5151
* @return {array}
5252
*/
@@ -70,6 +70,12 @@ function replaceString(str, match, fn) {
7070

7171
// Apply fn to all odd elements
7272
for (var i = 1, length = result.length; i < length; i += 2) {
73+
/** @see {@link https://github.com/iansinnott/react-string-replace/issues/74} */
74+
if (result[i] === undefined || result[i - 1] === undefined) {
75+
console.warn('reactStringReplace: Encountered undefined value during string replacement. Your RegExp may not be working the way you expect.');
76+
continue;
77+
}
78+
7379
curCharLen = result[i].length;
7480
curCharStart += result[i - 1].length;
7581
result[i] = fn(result[i], i, curCharStart);

‎test.js‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,3 +158,15 @@ test('Will not through if first element of input is empty string', t => {
158158
});
159159
});
160160
});
161+
162+
test("Avoids undefined values due to regex", (t) => {
163+
const string = `hey you there`;
164+
const re = /(hey)|(you)/;
165+
166+
// Normal splits include undefined if you do this
167+
t.deepEqual(string.split(re), ["", "hey", undefined, " ", undefined, "you", " there"]);
168+
169+
t.notThrows(() => {
170+
replaceString(string, /(hey)|(you)/, x => x);
171+
});
172+
});

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /