tiara nane
tiara nane

Reputation: 91

Javascript: replace until word is found

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

Upvotes: 0

Views: 165

Answers (3)

Maxime Girou
Maxime Girou

Reputation: 1570

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))

Upvotes: 1

Pranav C Balan
Pranav C Balan

Reputation: 115222

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\()/, ''));

Upvotes: 0

ttulka
ttulka

Reputation: 10882

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);

Upvotes: 2

Related Questions