简体   繁体   English

在字符串中查找并从匹配字符串的列表中查找并替换为html标记

[英]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: 注意事项和附加说明:

  • Avoid using DOM manipulation like addClass, innerHTML, appendChild, as I would like to come up with an elegant solution within the render function of a component with in React 避免使用像addClass,innerHTML,appendChild这样的DOM操作,因为我想在React的组件的render函数中提出一个优雅的解决方案
  • Not to use a complete string regex solution as I am wanting to insert react DOM elements instead of manipulating and parsing the dom after the solution 不要使用完整的字符串正则表达式解决方案因为我想插入反应DOM元素而不是在解决方案之后操作和解析dom
  • I want to attach additional information to the span tags IE the react DOM elements to filter by these wrapped strings, for example ID's or native react events to that element 我想将附加信息附加到span标签IE,以反应DOM元素以通过这些包装的字符串进行过滤,例如对该元素的ID或本机反应事件
  • I must cater for matching sentences not just individual words. 我必须满足匹配句子而不仅仅是个别单词。
  • No browser requirements 没有浏览器要求
  • List of strings will always be unique and have no overlaps 字符串列表将始终是唯一的并且没有重叠
  • Not all strings in the list are within the body of text ( ;) ) 并非列表中的所有字符串都在文本正文(;)中)

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 👇 这是工作解决方案👇

编辑8nkp163270

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.

相关问题 替换标签内 HTML 字符串中的颜色字符串 - Replace color strings in HTML string within tags 使用 HTML 标签查找和替换字符串中的表达式 - Find and replace expression in a string with HTML tags 从HTML解析所有内容并找到一个字符串并替换,但是如果匹配则无法替换标签字符串 - parse all content from HTML and find a string and replace But cannot replace tags string if match 用 HTML 标签替换字符串中的特定字符 - Replace a specific character from a string with HTML tags 如何使用javascript(而不是标签或属性)替换字符串中所有匹配的纯文本字符串? - how to replace all matching plain text strings in string using javascript (but not tags or attributes)? 替换<a>HTML字符串中的</a>所有<a>标签</a> - Replace all <a> tags in HTML string 从数组中查找所有可能的匹配字符串和子字符串 - Find all possible matching string and sub-strings from an array 将 HTML 标签从 javascript 字符串分离成单独的字符串 - Separating HTML tags from a javascript string into individual strings 从字符串中替换所有出现的html标记和特殊的unicode字符 - Replace all occurrences of html tags and special unicode character from a string 用等效的HTML替换字符串。 除了<a>标签</a> - Replace string with HTML equivalent. Apart from <a> tags
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM