1

I have a web page that generates links for keywords. The links get generated on the web page like so:

https://www.example.com/?keywords=energy
https://www.example.com/?keywords=wind%20power

I'd like to change it so that the first character after the = (and the %20 when applicable) is uppercase:

https://www.example.com/?keywords=Energy
https://www.example.com/?keywords=Wind%20Power

Currently, I have been changing them to uppercase on a per keyword basis:

$(document).ready(function(){
    $('a').each(function(){
        this.href = this.href.replace('energy', 'Energy');
    });

    $('a').each(function(){
        this.href = this.href.replace('wind%20power', 'Wind%20Power');
    });
});

Is there a way to do this, but with any string? I've tried several regular expressions but cannot seem to find a regex for replacing the first character after the equals sign with its uppercase equivalent using javascript. For example I tried this (https://regex101.com/r/ybQbaE/1/), and then tried to dump it into my script on the page:

`$(document).ready(function(){
    $('a').each(function(){
        this.href = this.href.replace(\=.,\U$0);
    });
});`

Of course it didn't work because it's for PHP, but when I click on the ECMAscript Flavor on the regex tester it just replaces the equals sign and the first character after it with \U$0.

benzio
  • 13
  • 4

6 Answers6

1

If those are your only cases you can solve it with a simple one liner:

url="https://www.example.com/?keywords=wind%20power%20earth%20fire"
url.replace(/(=\w)|(\s\w)|(%20\w)/g,val=>val.toUpperCase())

For more information regarding Regexp patterns visit this. For more on the javascript replace function visit the Replace MSDN docs

  • 1
    This works like a charm. Thank you! And thanks for the links as well. I am definitely learning a lot about regular expressions. Much appreciated. – benzio Dec 19 '20 at 17:43
0

You can match an =, then use another replacer function inside which replaces contiguous alphabetical characters with their upper-case version:

$('a').each(function(){
    this.href = this.href.replace(
        /=(.+)/g,
        (_, keywords) => '=' + keywords.replace(
            /([a-z])([a-z]*)/gi,
            (_, initial, rest) => initial.toUpperCase() + rest.toLowerCase()
        )
    );
});

$('a').each(function(){
    this.href = this.href.replace(
        /=(.+)/g,
        (_, keywords) => '=' + keywords.replace(
            /([a-z])([a-z]*)/gi,
            (_, initial, rest) => initial.toUpperCase() + rest.toLowerCase()
        )
    );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="https://www.example.com/?keywords=energy">a</a>
<a href="https://www.example.com/?keywords=wind%20power">a</a>
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • 1
    What about using post 2010 technology? – NVRM Dec 19 '20 at 03:05
  • What do you mean? `.replace` works just fine, and the implicit return of arrow functions (an ES2015 feature) is really nice. I guess you could make the `'=' + keywords.replace` into a template literal, but that'd be too hard to read IMO – CertainPerformance Dec 19 '20 at 03:13
  • well, I left an answer about the usage of the built-in URL() parser. Maybe not the best way idk, but at least it's readable and even memorizable (As I did there, by head). – NVRM Dec 19 '20 at 03:45
0

No need to get fancy, use the URL() constructor!

let url = new URL("https://www.example.com/?keywords=wind%20power%20earth%20fire");

let params = url.searchParams.get('keywords')
console.log(params)

params.split(" ").forEach( (e) => {
    console.log(
      e[0].toUpperCase() + e.substring(1)
    )
  }
)
NVRM
  • 11,480
  • 1
  • 88
  • 87
0

Usually regex should be the last step, when there are no specific encoders/decoders left to help. (like in this case, decodeURIComponent or the URL constructor)

document.querySelectorAll('a').forEach(a=>{
    var url = new URL(a.href);
    var keywords = url.searchParams.get('keywords')
    if( keywords ){
      //Capitalize thanks to: https://stackoverflow.com/a/7592235/1683017
      keywords = keywords.replace(/(?:^|\s|["'([{])+\S/g, m => m.toUpperCase())
      url.searchParams.set('keywords', keywords )
      a.href = url.href;
    }
})
aliqandil
  • 1,673
  • 18
  • 28
0

I think this is simpler conceptually (for me anyway):

url.replace(/=.*/, k => k.replace(/[a-z]+/g, s => s.toUpperCase()))
pguardiario
  • 53,827
  • 19
  • 119
  • 159
  • That just replaces Everything after the '=' sign to upper case. I believe the op wanted to capitalize only the first letter after the '=' sign and also the first one after every space. – Mario Figueiredo Dec 22 '20 at 02:46
-1

If you want to match = or %20, you'll just want to modify your regex to include the %20 as an option, make sure you have the global flag set, and then pass a function to your replace function to uppercase the parts of the string that match.

let url = "https://www.example.com/?keywords=wind%20power%20earth%20fire";

let regex = /(?<=\=|%20)(.)/g;
url = url.replace(regex, function (match, capture) {
    return capture.toUpperCase();
})

console.log(url)
Amy Shackles
  • 158
  • 1
  • 6