gpt4 book ai didi

javascript - 如何根据特定条件搜索句子并替换?

转载 作者:行者123 更新时间:2023-12-02 09:03:06 30 4
gpt4 key购买 nike

我的意思是指针:_# _,而尖头句子:_# some dynamic words _

我想找到一个sentence

  • if (sentence contained pointer)然后remove pointer
  • const stringVal = "being _#kind_, I am a _#kind_ _#man_, I love _#kind_ people, _#kind_ people is very great";
    const searchSentence = "a kind man";

    提示: a kind man包含 two pointer,所以我必须对其进行 remove,因为 pointers中都存在 searchSentence,但是其他 pointers仍然存在,因为它们不在 searchSentence中。

    所以结果是:
    stringVal = "being _#kind_, I am a kind man, I love _#kind_ people, _#kind_ people is very great";

    我尝试了以下内容:
    searchSentence.trim().split(/\b\s+/).forEach(item => {
    stringVal = stringVal.replace(`_#${item}_`, item);
    });

    我的解决方案只删除 first pointer中存在的 stringVal

    注意: stringVal是动态的并且可以更改,因此仅应考虑条件,并且 searchSentence可能包含 one or more pointers,因此应将其全部删除。

    重要:应在 searchSentence值中找到 stringVal变量的值完全匹配,然后如果其中存在任何指针,则应将其删除。

    最佳答案

    您可以尝试以下解决方案。请注意类样本man 更改的两次出现。(我认为这是您的要求)

    //var searchSentence = "a kind sample man";
    //var stringVal = "I am a _#kind_ _#sample_ _#man_, I love _#kind_ people, _#kind_ people is very great. I am also a _#kind_ _#sample_ _#man_.";
    var searchSentence = "kind people is";
    var stringVal = "being _#kind_, I am a _#kind_ _#man_, I love _#kind_ people, _#kind_ people is very great";
    searchSentence.trim().split(/\b\s+/).forEach((item, index) => {
    let splitSearch = searchSentence.split(" ")[index + 1];
    stringVal = stringVal.replace(new RegExp(`_?#?${item}_? (?=_?#?${splitSearch}_?)`,'g'), item + " ")
    stringVal = stringVal.replace(new RegExp(`(?<=${item} )_?#?${splitSearch}_?`, 'g'), splitSearch);
    });
    console.log(stringVal)

    关于javascript - 如何根据特定条件搜索句子并替换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61570646/

    30 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com