Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
});

>Solution :

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).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading