Home > Net >  RegEx query to move random string at the end of URLs
RegEx query to move random string at the end of URLs

Time:06-08

For example, see image below. I am trying to input this into Google Analytics and pull off a spreadsheet of all the /blog URLs. However, when I export them, there is a lot of URLs with a random string starting with '?' such as 'to-he-qualification?queryID=0575ca017c1e066b8e5cfc5e886a1261&objectID=9846-0'

Trying to figure out a RegEx query to simply to remove the '?' and the random string afterwards, leaving me with just '/blog/he-qualification'

Please help :D

Example URL image (I'm not allowed to embed images apparently)

CodePudding user response:

You need to search for ? followed by anything until the end of the string or the line. So this can be done with this regex: \?.*$

  • \? is to search for the ? char. The backslash is used to escape the question mark which has a signification in the regex syntax and we don't want that, we want to match the question mark character.

  • . is to match any char once. Adding the * behind, leading to .* means that this character can be zero or multiple times.

  • $ matches the end of the string or the end of the line if the regex is using the m flag for multiple lines. That's what I used below as the input is the list of all your URLs.

You can test the regex here: https://regex101.com/r/Qr3mCS/1

Or directly run this little snippet of HTML and JavaScript:

let urlsInput = document.getElementById('urls-input');
let cleanUpButton = document.getElementById('cleanup-button');

cleanUpButton.addEventListener('click', function (event) {

    urlsInput.innerHTML = urlsInput.innerHTML.replace(/\?.*$/gm, '');

}, false);
<button id="cleanup-button">Click to clean-up below</button>

<pre><code id="urls-input">g/career-in-payroll?infinity=ict2~net~gaw~cmp~16522683313~ag~~ar~~kw~~mt~~acr~2115324139
g/career-project-management?query|D=fcc34fa7cOec66f7eb661f85c714bcad&objectID=7733-0
g/category/careers-advice/page/3
g/category/news/page/2
g/category/success-stories/
g/choose-career-public-relations
g/considering-career-nutritionist?querylD=O0fa31b26a55017303605932301909854&objectID=7273-1
g/dealing-with-anxiety-studying
g/dealing-with-stress
g/denis-mature-a-level-student-experience?querylD=8a10a54b113793066c6e5c0a3a9b3d 1b&objectID=97009-1
g/gcses-for-adults?querylD=1db4c986716a4d0872e4598c1ba8c7b3&objectID=94722-0</code></pre>

  • Related