Home > Enterprise >  Change all divs content if contains a specific word and a number greater than 1
Change all divs content if contains a specific word and a number greater than 1

Time:01-22

Good evening!

I have a lot of divs with class ".goods__variants" and different text inside. So if i have "1 color", its correct, but if i have 15, i see "15 color", so not correctly. I need to change all divs that contain inside number more than 1 and replace text "color" to "colors".

I'll try to make like this, but I wouldn't want to write every line of value for every digit. How can this be done more dynamically for all digits? Thanks a lot!

Code:

$('.goods__variants').each(function() {
   var text = $(this).text();
   text.indexOf("4 Farbe") >= 0 ? text = text.replace('4 Color', '4 Colors') : null;
   $(this).text(text);
});

CodePudding user response:

To check if pluralization is needed, you only need to check if the standalone number 1 exists. If it doesn't, then change color to colors.

$('.goods__variants').each(function() {
  const original = $(this).text();
  if (!/\b1\b/.test(original)) {
    $(this).text(original.replace(/\bcolor\b/, 'colors'));
  } // add an else here if you want to change colors back to color
});

\b1\b surrounds 1 with word boundaries so that only the standalone number 1 is matched.

\bcolor\b surrounds color with word boundaries so that only the standalone word color is matched (and not, for example, the color in colors).

  • Related