Remove all characters on line after a specific character in multiline textarea

Viewed 38

Say I have a multi line text area with one URL per line, and I want to remove all the queries and tags after the actual link on each line, how can I accomplish this? I was thinking of just looking for a "?" and just erasing the "?" along with all the content after it. I need to loop through all the lines and output the URLS without the queries.

I found this script that can remove the characters after the ? but i am not sure how to make it work with a multiline text box.

ORIGINAL

<textarea>
https://www.amazon.com/gp/product/B076736W8H?pf_rd_p=c2945051-950f-485c-b4df-15aac5223b10&pf_rd_r=9WBS7FV4YHRG3SFC42GK
https://www.amazon.com/dp/B07FGG4SNM/ref=sspa_dk_detail_6?psc=1&pd_rd_i=B07FGG4SNM&pd_rd_w=LD3nX&pf_rd_p=21517efd-b385-405b-a405-9a37af61b5b4&pd_rd_wg=L6K9T&pf_rd_r=RZJNTFFGASGBYNA71403&pd_rd_r=8d24e9dc-1470-11e9-a15a-092e7e681a0e
<textarea/>

DESIRED OUTPUT

<textarea>
https://www.amazon.com/gp/product/B076736W8H
https://www.amazon.com/dp/B07FGG4SNM/ref=sspa_dk_detail_6
<textarea/>

Script I found:

var s = '/Controller/Action';
var n = s.indexOf('?');
s = s.substring(0, n != -1 ? n : s.length);
document.write(s);

Any help is appreciated! This is my first little project in Html/JS.

1 Answers

You can use a global regular expression to match lines which start with http and contain a ?, and replace the whole line with only the part before the ?:

const textarea = document.querySelector('textarea');
textarea.value = textarea.value.replace(/^(http[^?]+)\?.+$/gm, '$1');
textarea {
  width: 100%;
}
<textarea>
https://www.amazon.com/gp/product/B076736W8H?pf_rd_p=c2945051-950f-485c-b4df-15aac5223b10&pf_rd_r=9WBS7FV4YHRG3SFC42GK
https://www.amazon.com/dp/B07FGG4SNM/ref=sspa_dk_detail_6?psc=1&pd_rd_i=B07FGG4SNM&pd_rd_w=LD3nX&pf_rd_p=21517efd-b385-405b-a405-9a37af61b5b4&pd_rd_wg=L6K9T&pf_rd_r=RZJNTFFGASGBYNA71403&pd_rd_r=8d24e9dc-1470-11e9-a15a-092e7e681a0e
</textarea>

The pattern

^(http[^?]+)\?.+$

means:

  • ^ - Match the start of the string
  • (http[^?]+) - Match and capture a group containing
    • http[^?]+ - http, followed by non-? characters
  • \? - Match a literal ?
  • .+$ - Match the rest of the characters in the line

And replace with $1, the first captured group.

Related