简体   繁体   English

ReactJS:从数组中查找和替换字符串

[英]ReactJS: Find and Replace String from an Array

Part of my tool allows a user to enter a string into a textfield, check if any words entered match with a preset array.我的工具的一部分允许用户在文本字段中输入字符串,检查输入的任何单词是否与预设数组匹配。

If the user's string contains a name object in the array then I want it to be replaced with a link.如果用户的字符串在数组中包含名称 object,那么我希望将其替换为链接。

I've created the function and onClick it should get the user's content, loop through the array to see if any names match the user's content and then replace that name with a link.我已经创建了 function 和 onClick 它应该获取用户的内容,遍历数组以查看是否有任何名称与用户的内容匹配,然后用链接替换该名称。

Currently, it's only doing it per array object where as I need it to replace all and only return one string.目前,它只对每个数组 object 执行此操作,因为我需要它来替换所有内容并且只返回一个字符串。

  const generateContent = () => {
var arr1 = [{
link: 'https://www.link1.com/',
name: 'Link1'
}, {
  link: 'https://www.link2.com/',
    name: 'Link2'
}];

const findArrayItem =  arr1.find(obj => content.includes(obj.name))
const final = content.replaceAll(findArrayItem.name, "<a href=" + findArrayItem.link + ">" + findArrayItem.name + "</a>")

    setFinalContent(final)
  }

 const content = 'Link1Link2'; const generateContent = (content) => { var arr1 = [ { link: 'https://www.link1.com/', name: 'Link1', }, { link: 'https://www.link2.com/', name: 'Link2', }, ]; const final = arr1.reduce((a, b) => { return a.replaceAll(b.name, '<a href=' + b.link + '>' + b.name + '</a>'); }, content); return final; }; generateContent(content);

This is a possible implementation.这是一个可能的实现。 It triggers the change when you hit a space after the link name to avoid an endless replace loop.当您点击链接名称后的空格以避免无休止的替换循环时,它会触发更改。

 const { useState } = React // for inline use // import { useState } from 'react' // for normal use const linkMapping = [ { link: 'https://www.link1.com/', name: 'Link1' }, { link: 'https://www.link2.com/', name: 'Link2' } ] const replaceToLink = (text, linkMapping) => { return linkMapping.reduce((acc, { name, link }) => { return acc.replaceAll(`${name} `, `<a href="${link}">${name}</a> `) }, text) } const App = () => { const [value, setValue] = useState('') const handleChange = ({ target }) => { setValue(target.value) } return ( <div> <textarea value={value} onChange={handleChange} /> <div dangerouslySetInnerHTML={{ __html: replaceToLink(value, linkMapping) }} /> </div> ) } ReactDOM.render(<App />, document.getElementById('root'))
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.9.0/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.9.0/umd/react-dom.production.min.js"></script> <div id="root"></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM