在jQuery中查找括在括号中的文本

时间:2009-08-20 01:14:09

标签: javascript jquery

我在页面上有一些文字,我想找到并删除括号中的任何文字。 例如:

<td>here is [my text] that I want to look at</td>

所以我想获取该文本(我的文本),将其保存在变量中并将其从原位移除。

3 个答案:

答案 0 :(得分:1)

如果你正在使用jQuery,你可以在$('body')。text()上使用正则表达式,如\[(.+)\]

编辑:对不起,我可能会稍稍跳过这个问题给你这个答案。再考虑几分钟,并尝试用更多信息更新它。

答案 1 :(得分:1)

您可能会发现此任务并非那么简单。如果您在将文本发送到Web浏览器之前可以控制它,您可能希望在文本周围添加<span class='bracket'>[my text]</span>,那么您可以使用jQuery轻松地执行此类操作:

$(".bracket").each(function() {
  // store the data from $(this).text();
}).remove();

这可以使用正则表达式和jQuery来完成,但是有些问题可能会导致处理像<input name='test[one][]' />这样的属性中的文本。“简单”的正则表达式将是这样的:

$("td").each(function() {
  var $this = $(this);

  var html = $this.html();
  var bracketText = [];

  // match all bracketed text in the html - replace with an empty string
  // but push the text on to the array.

  html = html.replace(/\[([^\]]+)\]/g, function() { 
    bracketText.push(arguments[1]);
    return "";
  });

  // put the new html in away and save the data for later
  $this.html(html).data("bracketText", bracketText);
});

如果您确定在文本以外的标签内没有[],那么这样做的危险并不大。

答案 2 :(得分:0)

我最终做了以下事情:

      $('#formQuizAnswers td.question').each(function(){
         var header = $(this).text().match(/-.*-/);
         $(this).text($(this).text().replace(header,''));
});

我改变了我的文字,我搜索到它周围有破折号IE -My text-