String.replace weird behaviour

Hey. I’m trying to replace everything that starts with marker[0] and goes until \n but it doesn’t work. I’ve checked the regexp and it works just as I want but the input.replace doesn’t work. Can you pls help me with this one?

function solution(input, markers) {
  let regexp1 = '/'+markers[0]+'.*?(?=\\\\n)/gm';
 return input.replace(regexp1,'a')
};
solution("apples, plums % and bananas\npears\noranges !applesauce", ["%", "!"]);

You can’t pass variables into regex literals. Regex literals are not strings. You can build regexes from strings using new RegExp()

1 Like

I believe because you are passing a string not a regex into your first argument…

replace method, can not parse that string into a regex on its own. Your issue here is that you want to pass a variable as an item into your regexp.

Check the link below:

https://stackoverflow.com/questions/4029109/javascript-regex-how-to-put-a-variable-inside-a-regular-expression

I hope that was helpful!!

Done, still doesn’t work

function solution(input, markers) {
  let regexstring = markers[0]+'.*?(?=\\\\n)';
  let regexp1 = new RegExp(regexstring, 'gm');
  
  return input.replace(regexp1,'a');
};
solution("apples, plums % and bananas\npears\noranges !applesauce", ["%", "!"])

What do you think this will do? As far as I can see, it matches this pattern:

% and bananas

And replaces it with “a”, so you get

apples, plums a\npears\noranges !applesauce

It returns

"apples, plums % and bananas
pears
oranges !applesauce"

instead of replacing ‘% and bananas’ with ‘a’…