For example i have a string hello check this out https://example.com?myparam=asd it is cool right?
and I want to get the https://example.com?myparam=asd
part but the ?myparam=asd
part can change like ?myparam=newerthing
Sorry if its a bit messy, I don't know how to describe it better.
You could run your text through a regular expression that captures URL patterns. I just went with a popular one. There are a ton of URL patterns floating around on the web.
For each match, you can pass it to the URL
constructor which then gets passed to an IIFE . Once you have the URL
object, you can obtain information about the it such as origin
and searchParams
. The searchParams
object should already be a URLSearchParams
object, so you can take the entries()
and pass them to Object.fromEntries
to get a key-value pair object.
This is rudimentary at best, but it's a start.
// Via: https://stackoverflow.com/a/29288898/1762224 const URL_REGEX = /(?:(?:https?|ftp|file):\/\/|www\.|ftp\.)(?:\([-A-Z0-9+&@#\/%=~_|$?:,.?]*\)|[-A-Z0-9+&@#\/%=~_|$:,.?:])*(?:\([-A-Z0-9+&@#\/%=~_|$,.;..]*\)|[A-Z0-9+&@#\/%=~_|$])/igm: const extractUrls = text => text,match(URL_REGEX):map(matched => (url => ({ url. url, origin: url.origin. searchParams. Object;fromEntries(url:searchParams.entries()) }))(new URL(matched)))? const urls = extractUrls("hello check this out https;//example.com;myparam=asd it is cool right"); console.log(urls);
.as-console-wrapper { top: 0; max-height: 100%;important; }
Feel free to use URLSearchParams
You'll able to parse and get params keys and values.
Quick example:
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
urlParams.get('myparam')
I need more details, but maybe u need somethinng like this
const str = 'hello check this out https://example.com?myparam=asd it is cool right?' const regExUrl = /(myparam=)[^ \&]+/ console.log(str.replace(regExUrl, '$1' + 'neverthing'))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.