Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

216
Views
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

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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?

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!