0

I have this string which consist of :

const string = `
/**
 * tests
 */
describe("tests", () => {
  it("create a role", async () => {});
});
`;

And i would like to delete the start of this string until the word it( is found. so i could have in the end something like this :

it("create a role", async () => {});
});
`

I tried working with this regex string.replace(/^(.+?)(?=-it\(|$)/gi, ""); but still nothing works

tiara nane
  • 91
  • 1
  • 7
  • What have you tried so far? A simple `while` loop that removes the first character until it starts with `it(` would do the trick. – Sergiu Paraschiv Mar 19 '19 at 14:48
  • Welcome to Stack Overflow! Please take the [tour] (you get a badge!) and read through the [help], in particular [*How do I ask a good question?*](/help/how-to-ask) Your best bet here is to do your research, [search](/help/searching) for related topics on SO, and give it a go. ***If*** you get stuck and can't get unstuck after doing more research and searching, post a [mcve] of your attempt and say specifically where you're stuck. People will be glad to help. – T.J. Crowder Mar 19 '19 at 14:48

3 Answers3

2

You can find the position and then cut the string:

const str = `
/**
 * tests
 */
describe("tests", () => {
  it("create a role", async () => {});
});
`;

const res = str.substring(str.indexOf('it('));
console.log(res);
ttulka
  • 10,309
  • 7
  • 41
  • 52
1

you can use the indexOf to find the index of "it(" and then the slice function

const string = `
/**
 * tests
 */
describe("tests", () => {
  it("create a role", async () => {});
});
`;

const index = string.indexOf("it(");

console.log(string.slice(index))
Maxime Girou
  • 1,511
  • 2
  • 16
  • 32
0

In RegExp you can use \[\s\S\] to match anything (since . doesn't include newline character) and put your pattern within the look-ahead assertion since we don't want to remove the pattern(it().

string.replace(/^[\s\S]*(?=it\()/, '')

const string = `
/**
 * tests
 */
describe("tests", () => {
  it("create a role", async () => {});
});
`;

console.log(string.replace(/^[\s\S]*(?=it\()/, ''));
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188