[英]Find in string and from a list matching strings and replace with html tags
I am a little stumped by this but I want to achieve the following. 我有点难过,但我希望实现以下目标。
I have a large string and within that string I want to match against an array of strings and replace with markup tags. 我有一个大字符串,在该字符串中我想匹配一个字符串数组并替换为标记标记。
Take the following string: 请使用以下字符串:
The quick brown fox jumps over a lazy dog.
This is my list of strings ( which could be a whole sentence not just a word) I wish to match to the body of text: 这是我的字符串列表(可能是一个完整的句子而不仅仅是一个单词)我希望匹配文本正文:
['quick', 'brown', 'lazy dog', '.']
My result I am trying to achieve: 我想要实现的结果:
// ['The', <span>quick</span>, '<span>brown</span>', 'fox jumps over a' '<span>lazy dog</span>', '<span>.</span>]
Caveats and additional notes: 注意事项和附加说明:
Kinda the dataset I would be dealing with: https://codepen.io/nigel_manny/pen/omjxrx 有点我要处理的数据集: https : //codepen.io/nigel_manny/pen/omjxrx
Goodluck and thank you! 祝你好运,谢谢!
I think the trick here is to divide and conquer the string, finding and wrapping the word/sentence matched on the way with HTML element and repeat the process for each word/sentence. 我认为这里的技巧是划分和征服字符串,找到并包装与HTML元素在路上匹配的单词/句子,并为每个单词/句子重复该过程。
Walkthrough: 演练:
// Sample data
const str = "The quick brown fox jumps over a lazy dog.";
const words = ["quick", "brown", "lazy dog", ".", "missing word"];
Let's put str
in a array and in the beginning str
is the only element in the array. 让我们把str
放在一个数组中,在开头str
是数组中唯一的元素。
// Start
["The quick brown fox jumps over a lazy dog."]
// Iteration 1: replace all "quick" with span
// When matched, we split current element into three array elements
// Before match part + matched part + after match part
["The ", <span>quick</span>, " brown fox jumps over a lazy dog."]
// Iteration 2: replace all "brown" with span
["The ", <span>quick</span>, " ", <span>brown</span>, " fox jumps over a lazy dog."]
// Iteration 3: replace all "lazy dog" with span
["The ", <span>quick</span>, " ", <span>brown</span>, " fox jumps over a ", <span>lazy dog</span>, "."]
// Iteration 4: replace all "." with span
["The ", <span>quick</span>, " ", <span>brown</span>, " fox jumps over a ", <span>lazy dog</span>, "", <span>.</span>, ""]
// Iteration 5: replace all "missing word" with span, but this sentence doesn't exist, so output will remain same
["The ", <span>quick</span>, " ", <span>brown</span>, " fox jumps over a ", <span>lazy dog</span>, "", <span>.</span>, ""]
Here is the working solution 👇 这是工作解决方案👇
My proposal, with updated data, is (no more regex): 我提出的更新数据是(不再是正则表达式):
const text = 'Could it be improved where an ai suggests text books and notes which could help with a question (maybe based on keywords?) and then at the end the user rates the helpfulness of the suggestions, which helps the ai learn what to suggest. Taking lead from Medium articles, it would be awesome to be able to highlight text and it gives you suggestions of what to do with it (copy to clipboard, bookmark to my account etc) and also show me the most highlighted sections of each set of notes so i see what the community is finding most useful. I think linking to buy the paper version of the book is a weak and half hearted way to monitise this idea - why not go "full netflix" and get rid of the blockbusters model altogether. Scrap all the print titles and charge a subscription to be able to be able to access the extra revision information. In a Spotify freemium kind of way you could access the question banks for free but to get the revision notes/books etc you would pay. You would need a subscription model which worked for the amount of time someone is likely to find this information useful. Maybe micropayments solution would be better than a subscription?'; const matchingSentences = [ 'Could it be improved where an ai suggests text books and notes which could help with a question (maybe based on keywords?) and then at the end the user rates the helpfulness of the suggestions, which helps the ai learn what to suggest.', 'Taking lead from Medium articles, it would be awesome to be able to highlight text and it gives you suggestions of what to do with it (copy to clipboard, bookmark to my account etc) and also show me the most highlighted sections of each set of notes so i see what the community is finding most useful.', 'I think linking to buy the paper version of the book is a weak and half hearted way to monitise this idea - why not go "full netflix" and get rid of the blockbusters model altogether.', 'Scrap all the print titles and charge a subscription to be able to be able to access the extra revision information.' ]; var result = []; var startingIdx = 0; matchingSentences.forEach(function(e, i) { var idx = text.indexOf(e); if (idx != -1) { if (idx != startingIdx) { result.push(text.substr(startingIdx, e.length)); } var str = '<span>' + e + '</span>'; result.push(str); startingIdx += (e.length + 1); } }); if (startingIdx < text.length) { result.push(text.substr(startingIdx)); } console.log(result);
you can split the string and then match every word with list elements and store them in a separate list. 您可以拆分字符串,然后将每个单词与列表元素匹配,并将它们存储在单独的列表中。
your code may look like this. 你的代码可能看起来像这样。
const stringText = 'The quick brown fox jumps over a lazy dog.';
const matchList = ['quick', 'brown', 'lazy', '.'];
const splittedText = stringText.replace('.', ' .').split(' ');
const matchedSplittedText = splittedText.map(word => matchList.includes(word) ? handleWord(word) : word);
The imperative and naive way would be to cycle through each word in the array and check the appearances in the sentence: 必要和天真的方法是循环遍历数组中的每个单词并检查句子中的外观:
const string = "The quick brown fox jumps over a lazy dog. A full sentence.";
const replaceWords = ['quick', 'brown', 'lazy', '.', 'A full sentence.'];
const stringAsArray = string.replace('.', ' .').split(' ');
const splittedReplaceWords = replaceWords.flatMap(word => word.replace('.', ' .').split(' '));
const jsxEnhancedText = splittedReplaceWords.map(word => {
if(stringAsArray.indexOf(word) > -1) {
return React.createElement('span', props, word);
}
return word;
})
React.createElement
is just the non JSX variant. React.createElement
只是非JSX变体。 React.createElement('span', props, word)
takes an element as the first parameter (eg 'span' or a custom one), props
as an array as second parameter and then the children (in this case the word). React.createElement('span', props, word)
将一个元素作为第一个参数(例如'span'或自定义参数),将props
作为数组作为第二个参数,然后将子元素(在本例中为单词)。 See https://reactjs.org/docs/react-api.html#createelement for more information on this. 有关详细信息,请参阅https://reactjs.org/docs/react-api.html#createelement 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.