在单独的<tag>中包装匹配的字符串

时间:2016-01-17 06:01:53

标签: jquery

我在div中有一个字符串,还有一个输入框,用户可以在其中键入值。我想要的是,如果用户键入&#34; some&#34;在<input>中,因为字符串已经包含&#34;某些&#34;,我想把它放在&#34;一些&#34;使用其他<tag>,例如<div>this is <i>some</i>string!</div>

<div>this is some string!</div>

我尝试使用<div>indexOf()中识别匹配的userinput字符串,不确定它是否正确。下面是小提琴链接(不完整小提琴)。需要提示如何完成此操作!

2 个答案:

答案 0 :(得分:1)

使用替换功能:

str_to_replace = 'some';
current_string = 'this is some string!';
replaced_string = current_string.replace(str_to_replace, '<i>' + str_to_replace + '</i>');

如果您想多次阻止字符串换行,请使用:

str_to_replace = 'some';
current_string = 'this is some string!';

// check if we already have wrapped str_to_replace in the i tag
if( current_string.indexOf('<i>' + str_to_replace  + '</i>') == -1 )  {
    replaced_string = current_string.replace( str_to_replace, '<i>' + str_to_replace + '</i>' );
}

答案 1 :(得分:1)

 $(document).ready(function () {
        var replaced_string;
        var str_to_replace;
        var current_string;
        $('#text_inp').keyup(function () {
            str_to_replace = $('#text_inp').val();
            current_string = $('#div_test').text();
            var regex = new RegExp('\\b(' + str_to_replace + ')\\b', 'gim');
            replaced_string = current_string.replace(regex, '<i style="color:red">$1</i>');
            $('#div_test').html(replaced_string)
        });
    });

html代码

 <div id="div_test">this is some string!

Ever needed custom formatted sample / test data, like, bad? Well, that's the idea of this script. It's a free, open source tool written in JavaScript, PHP and MySQL that lets you quickly generate large volumes of custom data in a variety of formats for use in testing software, populating databases, and... so on and so forth.

This site offers an online demo where you're welcome to tinker around to get a sense of what the script does, what features it offers and how it works. Then, once you've whet your appetite, there's a free, fully functional, GNU-licensed version available for download. Alternatively, if you want to avoid the hassle of setting it up on your own server, you can donate $20 or more to get an account on this site, letting you generate up to 5,000 records at a time (instead of the maximum 100), and let you save your data sets. Click on the Donate tab for more information. 


</div>

<input  type="text" id="text_inp"/>