Разбейте строку на текстовые / http ссылки - PullRequest
2 голосов
/ 15 июля 2010

Я пытаюсь взять строку текста и создать из нее массив, чтобы строка:

var someText='I am some text and check this out!  http://blah.tld/foo/bar  Oh yeah! look at this too: http://foobar.baz';

введите здесь магическое регулярное выражение и

массив будет выглядеть так:

theArray[0]='I am some text and check this out!  '
theArray[1]='http://blah.tld/foo/bar'
theArray[2]='  Oh yeah! look at this too: '
theArray[3]='http://foobar.baz'

Я в растерянности, любая помощь будет принята с благодарностью

- Eric

Ответы [ 2 ]

2 голосов
/ 15 июля 2010

Разделение по регулярному выражению URL (спасибо @Pullet за указание на недостаток):

var urlPattern = /(https?\:\/\/\S+[^\.\s+])/;
someText.split(urlPattern);

Давайте разберем регулярное выражение:)

(https?    -> has "http", and an optional "s"
\:\/\/     -> followed by ://
\S+        -> followed by "contiguous" non-whitespace characters (\S+)
[^\.\s+])  -> *except* the first ".", or a series of whitespace characters (\s+)

Выполнение вашего образца текстат,

["I am some text and check this out!  ",
"http://blah.tld/foo/bar",
"  Oh yeah! look at this too: ",
"http://foobar.baz",
""]
0 голосов
/ 15 июля 2010

Попробуйте:

<script type="text/javascript">
    var url_regex = /((?:ftp|http|https):\/\/(?:\w+:{0,1}\w*@)?(?:\S+)(?::[0-9]+)?(?:\/|\/(?:[\w#!:.?+=&%@!\-\/]))?)+/g;
    var input = "I am some text and check this out!  http://blah.tld/foo/bar  Oh yeah! look at this too: http://foobar.baz";

    var results = input.split(url_regex);
    console.log(results);
</script>

results =

["I am some text and check this out! ",
"http://blah.tld/foo/bar",
" Oh yeah! look at this too: ",
"http://foobar.baz", ""]

Вы также можете обрезать отдельные результаты, чтобы не было начальных и конечных пробелов в записях, не относящихся к URL.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...