gpt4 book ai didi

javascript - 根据单词数组替换句子中所有出现的特定单词

转载 作者:行者123 更新时间:2023-11-30 11:31:01 24 4
gpt4 key购买 nike

我有一个这样的数组

var excludeWords = ["A", "ABOUT", "ABOVE", "ACROSS", "ALL", "ALONG", "AM", "AN", "AND", "ANY", "ASK", "AT", "AWAY", "CAN", "DID", "DIDN'T", "DO", "DON'T", "FOR", "FROM", "HAD", "HAS", "HER", "HIS", "IN", "INTO", "IS", "IT", "NONE", "NOT", "OF", "ON", "One", "OUT", "SO", "SOME", "THAT", "THE", "THEIR", "THERE", "THEY", "THESE", "THIS", "TO", "TWIT", "WAS", "WERE", "WEREN'T", "WHICH", "WILL", "WITH", "WHAT", "WHEN", "WHY"];

所以 Im 试图创建一个函数或任何快速的方法来从句子中删除上述单词的出现。不使用任何循环我怎样才能快速实现这一目标。

他们让我现在就做

var excludeWords = ["A", "ABOUT", "ABOVE", "ACROSS", "ALL", "ALONG", "AM", "AN", "AND", "ANY", "ASK", "AT", "AWAY", "CAN", "DID", "DIDN'T", "DO", "DON'T", "FOR", "FROM", "HAD", "HAS", "HER", "HIS", "IN", "INTO", "IS", "IT", "NONE", "NOT", "OF", "ON", "One", "OUT", "SO", "SOME", "THAT", "THE", "THEIR", "THERE", "THEY", "THESE", "THIS", "TO", "TWIT", "WAS", "WERE", "WEREN'T", "WHICH", "WILL", "WITH", "WHAT", "WHEN", "WHY"];
var sentence = "The first solution does not work for any UTF-8 alphaben. (It will cut text such as Привіт). I have managed to create function which do not use RegExp and use good UTF-8 support in JavaScript engine. The idea is simple if symbol is equal in uppercase and lowercase it is special character. The only exception is made for whitespace.";

$(excludeWords).each(function(index, item) {
var s = new RegExp(item, "gi");
sentence = sentence.replace(s, "");
});
alert(sentence);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

但是有没有比循环更好的解决方案呢??

基于评论更多细节..

它永远不应该删除单词的一部分。它应该只替换一个完整的单词

最佳答案

你快到了。诀窍是将所有单词组合成一个大的正则表达式,只进行一次替换。 \\b 确保您实际上替换了整个单词,而不仅仅是子字符串。

var excludeWords = ["A", "ABOUT", "ABOVE", "ACROSS", "ALL", "ALONG", "AM", "AN", "AND", "ANY", "ASK", "AT", "AWAY", "CAN", "DID", "DIDN'T", "DO", "DON'T", "FOR", "FROM", "HAD", "HAS", "HER", "HIS", "IN", "INTO", "IS", "IT", "NONE", "NOT", "OF", "ON", "One", "OUT", "SO", "SOME", "THAT", "THE", "THEIR", "THERE", "THEY", "THESE", "THIS", "TO", "TWIT", "WAS", "WERE", "WEREN'T", "WHICH", "WILL", "WITH", "WHAT", "WHEN", "WHY"];

var sentence = "The first solution does not work for any UTF-8 alphaben. (It will cut text such as Привіт). I have managed to create function which do not use RegExp and use good UTF-8 support in JavaScript engine. The idea is simple if symbol is equal in uppercase and lowercase it is special character. The only exception is made for whitespace.";

var re = new RegExp(`\\b(${excludeWords.join('|')})\\b`, 'gi');
sentence = sentence.replace(re, "");
console.log(sentence);

请注意,这最终会在字符串中创建连续的空格。可以使用 replace(/\s+/g, ' ').trim() 轻松删除它们。

关于javascript - 根据单词数组替换句子中所有出现的特定单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46219537/

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