Home > front end >  Replace part of a string and upper case the result
Replace part of a string and upper case the result

Time:02-12

everything good? I would like some help from you, I have the following scenario:

STRING_ONE:
       string_two
   STRING_three     :
                   string_four:
    stringfive:

I need to identify words from the beginning of the line that end with :

after identifying the words, I need to erase the spaces and convert them to uppercase, i tried doing some regex but as the words change I can't set the default for the replacement because i need to keep the same word, just removing the spaces and converting to capital letters

The result I'm trying to get is this:

STRING_ONE:
       string_two
   STRING_three     :
STRING_FOUR:
STRINGFIVE:

I can capture the words that match this pattern, with the following regex, but I don't know how to replace it by just erasing the spaces, keeping the rest of the string the same, and doing the upper case

^.*\b:

I tried to replace like this but it didn't work

"$1".toUpperCase()

Can anyone help please? Thanks!

CodePudding user response:

As you are not really replacing anything but instead you are looking for a pattern I used the pattern in a String.prototype.match() to identify the lines in which .trim() and .toLowerCase() need to be applied. The .split("\n") turns the initial string into an array over which I can then .map() the individual lines. At the end I .join() everything together again.

const str=`STRING_ONE:
   string_two
   STRING_three     :
               string_four:
stringfive:`;

console.log(str
   .split("\n")
   .map(s=>s.match(/^\s*\w :\s*$/) && s.trim().toUpperCase() || s )
   .join("\n")
);

Our regex patterns differ slightly:

  • while yours (/^.*\b:/) will match any line that has at least one word-end followed by a colon in it
  • mine (/^\s*\w :\s*$/) is stricter and demands that there is exactly one word followed by a colon in a line that can optionally be padded by any number of whitespace characters on either side.
  • Related