N
N
No Name2018-06-07 23:09:29
JavaScript
No Name, 2018-06-07 23:09:29

How to split a string into text and links?

There is a line like:
I have a link\n for you https://google.com.\n\n Also I have this link http://some.net.\n\n\n Some text ftp://test .net, ftps://test-2.de!
How can I split this string into an array of substrings so that links and regular text are separate in the output?
In this case, the sequence of text and links should be preserved, such as:

['I have a link\n for you ', 'https://google.com', '\n\n Also I have this link' ]

I found a regular expression that can extract links from text separately, but splits the text as described above:
(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Interface, 2018-06-07
@alienworkshop

const str = 'I have a link\n for you https://google.com.\n\n Also I have this link http://some.net.\n\n\n Some text ftp://test.net, ftps://test-2.de!';
// немного изменил RegExp убрав запоминающие скобки
const regExp = /(?:http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(?:\/\S*)?/g;
const textParts = str.split(regExp);
const links = str.match(regExp);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question