Home > other >  Removing specific element from string but only in line that contains another specific element JS
Removing specific element from string but only in line that contains another specific element JS

Time:12-08

Not sure if I phrase the question correctly so here is an example

let string = "Test text ab/c test
Test t/est
### Test/
Test t/test
Test test"

I'm looking to remove / from only line that contains ### in it so it ends up like this:

Test text ab/c test
Test t/est
### Test
Test t/test
Test test

I assume I can use

mystring.replace(/\/g, '')

But how do I specify that it needs to remove \ only in the line with ###

CodePudding user response:

You can split on newlines and then join them back again.

let string = `Test text ab/c test
Test t/est
### Test/
Test t/test
Test test
Test// ### test / 
`

const parts = string.split("\n")
  .map(s => s.includes("###") ? s.replace(/\//g, '') : s)
  .join("\n");
console.log(parts);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You can use

string.replace(/(?<=###.*)\/|\/(?=.*###)/g, '')

The (?<=###.*)\/|\/(?=.*###) regex matches a / char that is either preceded with ### and any zero or more non-line break chars, or followed with zero or more non-line break chars and then ###.

See this JavaScript demo:

let string = "Test text ab/c test\nTest t/est\n### /T/e/s/t/\nTest t/test\nTest test"
console.log(string.replace(/(?<=###.*)\/|\/(?=.*###)/g, ''))
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Another solution: split the stirng into lines, then map the resulting array and remove all / chars in the items that includes the ### substring, and then join the string back:

let string = "Test text ab/c test\nTest t/est\n### /T/e/s/t/\nTest t/test\nTest test"
console.log( string.split("\n").map(line => line.indexOf('###') > -1 ? line.replace(/\//g, '') : line).join("\n") )
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

.replace() the whole segment then return everything but \/ (the \ is prefixed to / in order to escape it.

const str = `
  Test text ab/c test
  Test t/est
  ### Test/
  Test t/test
  Test test`;

const rgx = /(###. )\//gm;
const sub = `$1`;

console.log(str.replace(rgx, sub));
<iframe name="sif4" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related