javascript - How to replace certain words in a variables in JavaScript
问题描述
The code below works very fine and replaces certain variables in the div. Eg food is replaced by bolded food is ready etc.
<script>
$(document).ready(function(){
$('div').html( $('div').html().replace(/food/g, '<strong>food is ready</strong>') );
$('div').html( $('div').html().replace(/meat/g, '<strong>good meat</strong>') );
$('div').html( $('div').html().replace(/milk/g, '<strong>best milk</strong>') );
});
</script>
<div> hello do you have food, what about meat. I will also need milk. and please make them bold.</div>
Here is my issue: I want to implement the same functionality above using inputted data from form variables. Eg. I want if type certain words and it contains food, milk etc. let them be replaced with their bolded equivalents in the sentence as I type. I have tried the code below but cannot get it to work.
<script>
$(document).ready(function(){
$('.message').keyup(function(){
var message = $('.message').val();
$('.result').html( $('.message').html().replace(/food/g, '<strong>food is ready</strong>') );
$('.result').html( $('.message').html().replace(/meat/g, '<strong>good meat</strong>') );
$('.result').html( $('.message').html().replace(/milk/g, '<strong>best milk</strong>') );
});
});
</script>
<input type='text' id='message' class='message'>
//Display all the typed sentence and replace their matched word with their bolded equivalents
<div class="result"></div>
</script>
解决方案
我没有测试以下代码,但它应该可以正常工作。
<script>
$(document).ready(function(){
$('.message').keyup(function(){
var message = $('.message').val();
var output = message.replace(/food/g, '<strong>food is ready</strong>').replace(/meat/g, '<strong>good meat</strong>').replace(/milk/g, '<strong>best milk</strong>'); //chained replace()
$('.result').html( output );
});
});
</script>
<input type='text' id='message' class='message'>
//Display all the typed sentence and replace their matched word with their bolded equivalents
<div class="result"></div>
</script>
这两个问题是:
- 在设置输出值时使用非链式替换函数,导致覆盖旧规则
- 使用
$('.message').html()
而不是message
推荐阅读
- java - Admob 插页式单例模式 java.lang.NullPointerException:
- php - 如何在我的垃圾邮件蜜罐中执行 PHP
- javascript - 检查常用下拉项(JavaScript、jQuery)
- java - android中的图像处理
- python - 为每一行在数据框中的多列中查找唯一值
- phpstorm - 如何消除此错误或禁用 WebStorm 或 PhpStorm 中的检查?
- c# - Windows服务突然停止工作并在服务器重新启动后正常工作
- tfs - 如何在 TFS 查询编辑器中构建查询以显示故事处于活动状态不到 10 分钟
- r - 在 R 中对重复项的类型进行分类
- r - 使用 Stata 和 R 绘制相同的随机数