首页 > 解决方案 > 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>

标签: javascript

解决方案


我没有测试以下代码,但它应该可以正常工作。

<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>

这两个问题是:

  1. 在设置输出值时使用非链式替换函数,导致覆盖旧规则
  2. 使用$('.message').html()而不是message

推荐阅读