简体   繁体   中英

jQuery - replace text formatted

<pre class="article">
    aaa aaa aaabbb
</pre>
(function ($) {
    var test = $("pre.article");
    test.html(test.text().replace(/aaa/g, '<span class="aaa">111</span>'));
});
})(jQuery)

Fiddle example

how to keep the results into: 111 111 aaabbb
please help me ....

You can add a \\s to the end of the search text to only look for that pattern with any white space character after the pattern.

.replace(/aaa\\s/g, '<span class="aaa">111</span>')

To keep the space without having to add it back in use \\b, which anchors to the end of a word.

.replace(/aaa\\b/g, '<span class="aaa">111</span>')

You can try different expressions on a string with a regex tester like regex101

Just make sure you catch also the space after the aaa :

 $(function() { var test = $("pre.article"); test.html(test.text() .replace(/aaa /g, '<span class="aaa">111</span> ')); }) 
 .aaa{color:red} 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <pre class="article"> aaa aaa aaabbb </pre> 

(and inside the replacement - add that space back)

JavaScript的第5行中,您要在替换的aaa和跨度的111之间留一个空格:

.replace(/aaa /g, '<span class="aaa">111 </span>'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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