Replace in a string doesn't work as intended

Viewed 76

I've written this function:

function solution(input, markers) {
  let inputcopy = input;
  let regexstring = markers[0]+'.*?(?=\\\\n)';
  let regexp1 = new RegExp(regexstring, 'gm');

  return inputcopy.replace(regexp1,'a');
};
console.log(solution("apples, plums % and bananas\npears\noranges !applesauce", ["%", "!"]));

Function needs to return

apples, plums a\npears\noranges !applesauce

but it returns

apples, plums % and bananas\npears\noranges !applesauce

What should I change?

2 Answers

Change \\\\n to \\n. It should work.

function solution(input, markers) {
        let inputcopy = input;
        let regexstring = markers[0]+'.*?(?=\\n)';
        let regexp1 = new RegExp(regexstring, 'gm');

        return inputcopy.replace(regexp1,'a');
    };

    solution("apples, plums % and bananas\npears\noranges !applesauce", ["%", "!"])

You could use the end of string sign $ and the multiline flag m together.

Otherwise, you do not need the multiline flag, but the right newline with only double backslashes \\n.

function solution(input, markers) {
  let inputcopy = input;
  let regexstring = markers[0]+'.*$';
  let regexp1 = new RegExp(regexstring, 'gm');

  return inputcopy.replace(regexp1,'a');
}
console.log(solution("apples, plums % and bananas\npears\noranges !applesauce", ["%", "!"]));
//                    apples, plums   a          \npears\noranges !applesauce

Related