子串选择器与jQuery? [英] substring selector with jquery?

查看:82
本文介绍了子串选择器与jQuery?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用jquery仅选择字符串的一部分?例如,我有一条文字

Is it possible to select only part of a string using jquery? For example I have a text

<p>Metuentes igitur idem latrones Lycaoniam magna parte campestrem</p>

现在,如果用户搜索一个字符串,我希望将其突出显示(例如,我们使用粗体标签)

So now if the user search for a string, I want it to be highlighted (we use a bold tag for example)

<p>Metuentes igitur idem latrones <b>Lycaoniam</b> magna parte campestrem</p>

然后,如果需要,我们可以恢复为原始字符串.

And then we can revert back to original string if needed.

  1. 第一个问题是我们是否可以使用jQuery选择这样的子字符串,并使用.css()之类的jQuery方法将样式应用于该元素.
  2. 第二个问题是,如果我们没有这样的选择器,我们如何通过字符串操作使用jQuery或javascript实现它
  1. The first question is whether we can select a substring like this using jQuery, and use jQuery method such as .css() to apply style to that element.
  2. The second question is if we don't have such selector, how can we achieve it using jQuery or javascript through string manipulation

谢谢.

已更新

感谢大家的努力.这是一个小程序,我正在寻找的最终结果 http://jsfiddle.net/TPg9p/3/干杯!

Thank for everyone effort. Here is a small program, final result of what I'm looking for http://jsfiddle.net/TPg9p/3/ Cheers!

推荐答案

纯jQuery无法做到这一点.您可以改为:

There is no way to do this with pure jQuery. You could do this instead :

var search = 'Lycaoniam';
var orig = $('p').html();
var highlighted = orig.replace(new RegExp(
    search.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'gi'
), '<b>$&</b>');
$('p').html(highlighted);

还原为原始文本:

$('p').html(orig);

search.replace(...)部分允许处理特殊字符: http://jsfiddle.net/wared/TPg9p/.

The search.replace(...) part allows to deal with special chars : http://jsfiddle.net/wared/TPg9p/.

这篇关于子串选择器与jQuery?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆