Trying to build a find and replace (kind of)

Hi friends,
I’ve never build an add on (or anzything else) before, and I’m trying to make something that replaces any number than precedes “kcal” in a web page. So for example, “2000 kcal” would become “x kcal”. I’ve figured out how to replace the word “kcal” with “x”, but I can’t figure out a way to change the preceding number.
Any help is very very much appreciated! As I said, I’m pretty new to this so apologies is this is a silly question :slight_smile:

It’s not a silly question, but because web pages have unpredictable structures, it may be difficult to find a universal solution.

There probably is a way to create a Regular Expression pattern to find:

(some number of digits)(space or maybe no space)(kcal)

and replace only the (some number of digits) group.

But I’m not very good with RegEx myself. :frowning_face:

You might be interested in this example extension: https://github.com/mdn/webextensions-examples/tree/master/emoji-substitution

As @jscher2000 mentioned you could do this with a regular expression (regex). The thing you are looking for is called a “Positive Lookahead”. This allows you to select something when it is followed by a specific pattern:

const text = "Let's replace 9876 kcal, but also 0 kcal. If we have 5 apples, it won't replace the number. 11111111kcal also works.";
console.log(text.replace(/\d+(?= ?kcal)/g, 'x'));
/* "Let's replace x kcal, but also x kcal. If we have 5 apples, it won't replace the number. xkcal also works." */

The crucial part is the regex: /\d+(?= ?kcal)/g. Let’s look at it in detail:

  • / : start of pattern
  • \d+ : one or more digits
  • (?=...) : Positive Lookahead. If its content follows the digits, select the digits
  • (space)?: optional space
  • kcal : The literal word “kcal”
  • / : end of pattern
  • g : select all occurrences (global flag)

If something is unclear, please ask. :slightly_smiling_face:

Happy coding,
Michael

1 Like