简体   繁体   中英

JavaScript Regex - Splitting a string into an array by the Regex pattern

Given an input field, I'm trying to use a regex to find all the URLs in the text fields and make them links. I want all the information to be retained, however.

So for example, I have an input of " http://google.com hello this is my content" -> I want to split that by the white space AFTER this regex pattern from another stack overflow question (regexp = /(ftp|http|https)://(\\w+:{0,1}\\w*@)?(\\S+)(:[0-9]+)?(/|/([\\w#!:.?+=&%@!-/]))?/) so that I end up with an array of [' http://google.com ', 'hello this is my content'].

Another ex: "hello this is my content http://yahoo.com testing testing http://google.com " -> arr of ['hello this is my content', ' http://yahoo.com ', 'testing testing', ' http://google.com ']

How can this be done? Any help is much appreciated!

First transform all the groups in your regular expression into non-capturing groups ( (?:...) ) and then wrap the whole regular expression inside a group, then use it to split the string like this:

var regex = /((?:ftp|http|https):\/\/(?:\w+:{0,1}\w*@)?(?:\S+)(?::[0-9]+)?(?:\/|\/(?:[\w#!:.?+=&%@!-/]))?)/;
var result = str.split(regex);

Example:

 var str = "hello this is my content http://yahoo.com testing testing http://google.com"; var regex = /((?:ftp|http|https):\\/\\/(?:\\w+:{0,1}\\w*@)?(?:\\S+)(?::[0-9]+)?(?:\\/|\\/(?:[\\w#!:.?+=&%@!-/]))?)/; var result = str.split(regex); console.log(result); 

You had few unescaped backslashes in your RegExp .

 var str = "hello this is my content http://yahoo.com testing testing http://google.com"; var captured = str.match(/(ftp|http|https):\\/\\/(\\w+:{0,1}\\w*@)?(\\S+)(:[0-9]+)?(\\/|\\/([\\w#!:.?+=&%@!-/]))?/g); var nonCaptured = []; str.split(' ').map((v,i) => captured.indexOf(v) == -1 ? nonCaptured.push(v) : null); console.log(nonCaptured, captured); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM