繁体   English   中英

如何提取字符串的特定部分并使其在 Javascript 中可点击?

[英]How do I extract a certain portion of a string and make it clickable in Javascript?

我有一个这种形式的 JS 字符串:

const pageContent = "He stood up and asked the teacher, "Can you elaborate the last point please? ".

我想将单词映射到页面并在视图中表示它,以便单词可点击。 有没有办法使用单词索引提取字符串的一部分,这样在任何单词之前和之后出现的任何标点符号都不可点击,但单词是可点击的? 例如单词Can是可点击的,但不是"Can ?

PS:我不能使用split函数将字符串转换为数组并进行映射,因为这可能会在某些极端情况下导致失败,并在转换回字符串时改变文本流。 我在一个单独的数组中拥有所有单词的索引以及字符串中每个单词的开始和结束索引,并且想要使用这些。

非常感谢任何帮助

简单地使用两个 for 循环并检查单词是否与排除的单词数组中的任何单词匹配

 const pageContent = 'He stood up and asked the teacher, "Can you elaborate the last point please?", Can you elaborate the last point please? ' const indexes = [ [35, 39], [9, 11] ] const excluded_words = ['"Can'] for (let i = 0, len = indexes.length; i < len; i++) { const word = pageContent.substring(indexes[i][0], indexes[i][1]); for (let i = 0, len = excluded_words.length; i < len; i++) { if (word.indexOf(excluded_words[i]) > -1) { console.log(word, " is excluded"); break; } if (i === len - 1) { console.log(word, " is included") } } }

暂无
暂无

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

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