Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string at character in JavaScript

I have three links :

"http//example.com/product/iphone?source=ac"
"http//example.com/product/samsung?source=tz"
"http//example.com/product/sony?source=sn"

I want to split the string to get two variables like so:

var link1 = 'http//example.com/product/iphone';
var link2 = '?source=ac'

// The others are similar
//var link1 = 'http//example.com/product/samsung';
//var link2 = '?source=tz'
//var link1 = 'http//example.com/product/sony';
//var link2 = '?source=sn'

Please give me your opinion, and help me in this case, I'm really new to javascript. It was difficult. Thank you everyone

like image 350
Miedkes Avatar asked Jan 23 '26 15:01

Miedkes


1 Answers

Here is a regex based approach using match:

var urls = ["http://example.com/product/iphone?source=ac", "https://example.com/product/iphone"];
for (var i=0; i < urls.length; ++i) {
    var parts = urls[i].match(/https?:\/\/[^?]+|\?.*/g);
    console.log(urls[i] + "\nurl => " + parts[0] + ", query => " + parts[1]);
}
like image 119
Tim Biegeleisen Avatar answered Jan 26 '26 05:01

Tim Biegeleisen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!