Javascript: replace until word is found

时间:2019-03-19 14:46:32

标签: javascript

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

3 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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))

答案 2 :(得分: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\()/, ''));