Answer the question
In order to leave comments, you need to log in
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' ]
(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
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 questionAsk a Question
731 491 924 answers to any question