(str: string)
| 182 | * @returns {ISegment[]} |
| 183 | */ |
| 184 | export function string2Segment(str: string): ISegment[] { |
| 185 | const segmentList: ISegment[] = []; |
| 186 | const urlTmp: { |
| 187 | [index: number]: { |
| 188 | text: string; |
| 189 | hasScheme?: boolean; |
| 190 | type: SegmentType.Url | SegmentType.Email; |
| 191 | }; |
| 192 | } = {}; |
| 193 | // match URL |
| 194 | const urlMatch = [...str.matchAll(LINK_REG)]; |
| 195 | const emailMatch = [...str.matchAll(EMAIL_REG)]; |
| 196 | |
| 197 | // If there is no URL/Email match, return directly to reduce unnecessary calculations |
| 198 | if (!urlMatch.length && !emailMatch.length) { |
| 199 | segmentList.push({ |
| 200 | type: SegmentType.Text, |
| 201 | text: str, |
| 202 | }); |
| 203 | return segmentList; |
| 204 | } |
| 205 | |
| 206 | urlMatch.forEach(element => { |
| 207 | const text = element[0]!; |
| 208 | const hasScheme = Boolean(element[15]); |
| 209 | const index = element.index!; |
| 210 | urlTmp[index] = { text, hasScheme, type: SegmentType.Url }; |
| 211 | }); |
| 212 | |
| 213 | emailMatch.forEach(ele => { |
| 214 | const text = ele[0]!; |
| 215 | const index = ele.index!; |
| 216 | urlTmp[index] = { text, type: SegmentType.Email }; |
| 217 | }); |
| 218 | |
| 219 | let seg = ''; |
| 220 | let cur = 0; |
| 221 | while (cur < str.length) { |
| 222 | if (cur in urlTmp) { |
| 223 | if (seg.length) { |
| 224 | segmentList.push({ |
| 225 | type: SegmentType.Text, |
| 226 | text: seg, |
| 227 | }); |
| 228 | seg = ''; |
| 229 | } |
| 230 | const { text, type } = urlTmp[cur]!; |
| 231 | segmentList.push({ |
| 232 | type, |
| 233 | text, |
| 234 | link: text, |
| 235 | }); |
| 236 | cur += text.length; |
| 237 | } else { |
| 238 | seg += str[cur]; |
| 239 | cur++; |
| 240 | } |
| 241 | } |
no test coverage detected