首页 > 解决方案 > Javascript:替换直到找到单词

问题描述

我有这个字符串,其中包括:

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

我想删除这个字符串的开头,直到it(找到这个词。所以我最终可以有这样的东西:

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

我尝试使用这个正则表达式string.replace(/^(.+?)(?=-it\(|$)/gi, "");,但仍然没有任何效果

标签: javascript

解决方案


你可以找到位置然后剪断字符串:

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

const res = str.substring(str.indexOf('it('));
console.log(res);


推荐阅读