Home > Software engineering >  Insert a string before all unknown parts of another string, when I know the strings before and after
Insert a string before all unknown parts of another string, when I know the strings before and after

Time:07-28

Or replace the string, while preserving the unknown part. This is just an example to simplify what I'm doing - say I have this string and I do not know the names or adjectives that will appear in it:

"Bob, really cool, also Gary, Hannah, really chill, and also Mary, John, Katie, really awesome"

I want to manipulate this string to read:

"Bob, really cool, also Gary and Hannah, really chill, and also Mary, John and Katie, really awesome"

Now I realize this is not grammatically correct but it is just an example as what I'm actually dealing with is a bunch of random numbers and codes.

What I have in the second part is "and" before the last name in each set where the names are described with an adjective, but the "and" is not before Bob.

I've tried:

var n = str.indexOf( /, (. ?), really/g);
newStr = str.substring(0, n)   " and "   floodString.substring(n);
console.log(newStr);

But running that will place an "and" before Bob, even though Bob doesn't have a comma before it like I asked, and it won't place the "and" anywhere else.

I've also tried str.replace() - but I don't want to replace the unknown string, just what is before it. Is there a way to preserve the strings in doing this, even when the string is of unknown length, unknown amount of names, and unknown sets of names matched with adjectives?

I know that somehow I can access the string in all the places I want if I somehow leverage ", [unknown name], really" while preserving the name, but I can't find a solution.

CodePudding user response:

This will do what you want from your example text, but is kind of specific to it so you might want to update your question with some actual sample data.

const input =
  "Bob, really cool, also Gary, Hannah, really chill, and also Mary, John, Katie, really awesome";
const target =
  "Bob, really cool, also Gary and Hannah, really chill, and also Mary, John and Katie, really awesome";

const output = input.replace(/, ([^,] , really)/g, " and $1");

console.log(output);
console.log(output === target); // true

/, ([^,] , really)/g

 ^^----------------- a comma and space
   ^---------------- start capturing to $1
    ^^^^^----------- anything apart from a comma
         ^^^^^^^^--- ", really"
                 ^-- finish capturing to $1

You might also find https://regex101.com/ useful for explaining what a regular expression is doing.

  • Related