For example I have strings which has multiple URLs.
var str = '"test.com","test2.com","test3.com/123,312","test4.com/123,312"'
I want to make array from this string.
at first I try to use split(",")
however some URL has ","
.
Is there any good idea to separate these?
5
Answers
If the string is split up by
","
(a quote, a comma, and a quote), then we have all the URL’s which can maintain their internal commas. Then we just have to remove any quotes that are left in each string of the arrayYes, you can employ a better approach to extract the URLs from the provided string. Since the URLs themselves might include commas, a basic comma-based split won’t be dependable. Instead, you can utilize regular expressions to locate the URLs within the string. Here’s an example:
This code uses a regular expression
/"([^"]+)"/g
to match strings enclosed in double quotes. Thematch
function returns an array of matched strings. Then, themap
function is used to remove the double quotes from each matched URL, creating the final array of URLs.Maybe just pull the url from inside the quotes?
You can do it by regex
str.match(/".*?"/g).
.Or by just doing
str.split(`",`).map(url => url.substring(1))
. Themap
part just drops the leading quote.In this case, you can use regular expressions to parse the string and extract the URLs. Here’s how you can achieve that using JavaScript:
Explanation:
str.match(/"(.*?)"/g) uses a regular expression to match text enclosed in double quotes and returns an array of matched strings.
.map(function(url) { return url.replace(/"/g, ”); }) removes the double quotes from each matched URL.
The urls array will contain the extracted URLs.
This code should work for your example string and handle URLs with commas as well.
You could use a regexp with a lookbehind assertion:
Also you could just split the string:
And a benchmark: