Home > Software design >  Lowercase everything after firts appearance of the character in a string in JS
Lowercase everything after firts appearance of the character in a string in JS

Time:07-28

Lowercase everything after firts appearance of the character in a string in JS

CodePudding user response:

One option is using regular expression:

str.replace(/\.([^.]*?)$/, (m) => m.toLowerCase())

CodePudding user response:

What you can do is splitting the string at ".", then convert the last part .toLowerCase() and finally .join() everything back together.

const t = 'qwery.ABC.ABC';

const parts = t.split(".");
console.log(parts.slice(0, -1).join(".")   "."   parts[parts.length - 1].toLowerCase());


One could argue whether that would actually be a cleaner variant. What usually isn't a bad idea for code readability is writing a utility function for that use case.

const t = "qwery.ABC.ABC";

const lastBitToLowerCase = (text, separator) => {
  const parts = t.split(separator);
  return `${parts.slice(0, -1).join(separator)}${separator}${parts[
    parts.length - 1
  ].toLowerCase()}`;
};

const result = lastBitToLowerCase(t, "."); // "qwery.ABC.abc"

CodePudding user response:

Regex using negative lookahead:

const re = /\.((?:.(?!\.)) )$/;
const inputs = [
"qwerty.ABC.ABC",
"yuiop.uu",
"QWERT.YUIOP"
];

inputs.forEach(input => {
   const result = input.replace(re, x => x.toLowerCase());
   console.log(input, "-->", result);
});

Regex described here: https://regexr.com/6qk6r

  • Related