3

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

1
  • Please share what you’ve tried so far. Commented Jun 23, 2022 at 5:24

4 Answers 4

1

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]);
}

Sign up to request clarification or add additional context in comments.

Comments

1
lnk = "http//example.com/product/iphone?source=ac"


let n = lnk.indexOf("?")

host = lnk.slice(0,n)
source = lnk.slice(n,)

console.log(`host = ${host}`)
console.log(`source = ${source}` )

gives me the output

host = http//example.com/product/iphone
source = ?source=ac

should work with all links as ? is a common factor

or are you looking for regex solution?

Comments

1

Consider using URL API to handle URLs properly:

const path = "http://example.com/product/iphone?source=ac";

const { origin, pathname, search, hash } = new URL(path);

const link1 = origin + pathname;
const link2 = search + hash;

console.log(link1);
console.log(link2);

Comments

1

I think you want to get the url and query?

let links = [
  "http//example.com/product/iphone?source=ac",
  "http//example.com/product/samsung?source=tz",
  "http//example.com/product/sony?source=sn"
]
links.forEach((x) => {
  let [ url, query ] = x.split("?")
  console.log(url, "?" + query)
})

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.