From d285722ddfc9b71cf8db49034675741c7456559f Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Tue, 19 May 2020 19:03:03 +1200 Subject: [PATCH] fix #66 --- src/lib/utils/structuretext.js | 32 ++++++++++++++++++++++++-------- test/structuretext.js | 20 ++++++++++++++++++++ 2 files changed, 44 insertions(+), 8 deletions(-) diff --git a/src/lib/utils/structuretext.js b/src/lib/utils/structuretext.js index 2c5e4f3..0a71351 100644 --- a/src/lib/utils/structuretext.js +++ b/src/lib/utils/structuretext.js @@ -1,8 +1,19 @@ const constants = require("../constants") function tryMatch(text, against, callback) { - let matched = text.match(against) - if (matched) callback(matched) + if (against instanceof RegExp && against.global) { + // if it's a global match, keep sending matches to the callback while the callback returns true + let matched + let ok = true + while (ok && (matched = against.exec(text))) { + ok = callback(matched) + } + against.lastIndex = 0 + } else { + // if it's a non-global match, just do the match. + let matched = text.match(against) + if (matched) callback(matched) + } } function textToParts(text) { @@ -19,11 +30,16 @@ function replacePart(parts, index, match, replacements) { function partsUsername(parts) { for (let i = 0; i < parts.length; i++) { if (parts[i].type === "text") { - tryMatch(parts[i].text, `@(${constants.external.username_regex})`, match => { - replacePart(parts, i, match, [ - {type: "user", text: match[0], user: match[1]} - ]) - i += 1 // skip parts: user + tryMatch(parts[i].text, new RegExp(`@(${constants.external.username_regex})`, "g"), match => { + if (match.index === 0 || parts[i].text[match.index-1].match(/\s/)) { // check that there's a space before the username + replacePart(parts, i, match, [ + {type: "user", text: match[0], user: match[1]} + ]) + i += 1 // skip the newly created part + return false + } else { + return true + } }) } } @@ -37,7 +53,7 @@ function partsHashtag(parts) { replacePart(parts, i, match, [ {type: "hashtag", text: match[0], hashtag: match[1]} ]) - i += 1 // skip parts: hashtag + i += 1 // skip the newly created part }) } } diff --git a/test/structuretext.js b/test/structuretext.js index 82b3355..ed31b3b 100644 --- a/test/structuretext.js +++ b/test/structuretext.js @@ -132,5 +132,25 @@ tap.test("entire structure works", childTest => { "special characters" ) + // email address + childTest.same( + structure("someaddress@gmail.com"), + [ + {type: "text", text: "someaddress@gmail.com"} + ], + "email address" + ) + + // email address + username + childTest.same( + structure("someaddress@gmail.com @gmail.com"), + [ + {type: "text", text: "someaddress@gmail.com "}, + {type: "user", text: "@gmail.com", user: "gmail.com"}, + {type: "text", text: ""} + ], + "email address" + ) + childTest.end() })