javascript - 在字符串中搜索不同的单词
问题描述
我需要搜索一个字符串以检查它是否包含存储在数组中的特定单词。如果字符串包含数组中的单词,则必须突出显示这些单词。在进入突出显示部分之前,如果找到数组中的单词,我尝试用虚拟文本替换字符串。代码如下:
let words:String[]=['cat','rat','bat'];
let text: String = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."
var newText = text.replace(words[0],"TEST");
所以 replace 方法中的单词数组应该从 0 递增到 < words.length。谁能建议一种方法来做到这一点?
解决方案
您应该了解循环。
let words:String[] = ['cat','rat','bat'];
let text: String = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."
let modifiedText = text;
words.forEach(word => {
modifiedText = modifiedText.replace(word,"TEST");
});
推荐阅读
- python - Python OAuth 客户端凭据授予类型返回 400,[错误:不支持的授予]类型,但 Curl 工作正常
- react-native - 长文本上的水平自动滚动反应原生
- python - 运行外部串行软件的并行实例
- c++ - 无法在 linux 上使用 vcpkg
- rest - Dot Net Core 计划作业的最佳实践,用于在封闭的 On Premise 环境中进行点对点集成
- machine-learning - 使用 catboost 提高 CNN 模型的准确性
- javascript - Mapbox API:如何获取给定邮政编码下的地址列表?
- bundler - bundle exec rake:在 Ubuntu 20.04 docker 主机上找不到命令
- date - 显然相同的日期未通过等效性测试
- cron - 如何使用 cron 安排任务每 x 小时运行一次?不和谐.py