使用jQuery </li>在<li>中换行文本

时间:2011-11-14 18:25:57

标签: javascript jquery regex

我有一个字符串:<li>&File</li>。我想要做的是分析li元素内的字符串以找到&符号的位置。一旦找到,我想将下一个字符包裹在span

这背后的逻辑相对简单。获取&的字符串位置,将其删除,然后在span中包含以下字符(即字符串位置+ 1)。

有人可以在jQuery中建议一个合适的方法来包装字符串的单个字符吗?我知道可以包装一个HTML块,但是可以像这样处理字符串,还是创建自定义函数会更好?

我应该提到&的位置也不会总是在字符串的开头。我正在考虑使用正则表达式来找到它的位置,因为我只想解析字符串中&符号的第一个第一次出现,从而使后来的出现不受影响。

&符号一个HTML实体 - 它只是&(而不是&amp;)。

最感激的任何帮助和见解......

6 个答案:

答案 0 :(得分:2)

因为它是一个字符,所以你可以使用.replace;不需要特殊的jQuery函数:http://jsfiddle.net/qr3pe/1/

$("li").each(function() {
    var html = $(this).html(),     // this element's html
        regexp = /&amp;(.)/,       // regexp (.html() returns &amp; even
                                   // if the source is &). `()` to capture.
        match = regexp.exec(html); // get the captured character

    if(!match) return; // no match; abort

    var replaced = html.replace(regexp,
                                "<span>" + match[1] + "</span>");

    $(this).html(replaced); // replace the html
});

答案 1 :(得分:1)

var text = $("li").text();
var location = text.indexOf("&");
if (location >= 0) { //if there is no &, location will equal -1
  var character = "<span>"+text.slice(location+1,location+2)+"</span>";
  text = text.slice(0,location)+character+text.slice(location+2);
}

如果你想要的话,你可能会把它全部放到一行,但我把它分开以便于阅读。

http://jsfiddle.net/q7GA5/1/

答案 2 :(得分:1)

var string = '<li>&File</li>';
var el = $(string);
el.html(el.text().replace(/&(.?)/, "<span>$1</span>"));
$(document.body).append(el);

http://jsfiddle.net/8whDz/

答案 3 :(得分:1)

如果我正确地解释了您的问题,那么这应该有效。 (JsFiddle

$(document).ready(function() {  
   var m = $('#test').html();  
   var n = m.indexOf('&amp;')  //Of course, you could simply use '&' here, everything else being same.
   var spanLetter = m.substr(n+5, 1);  
   /* Note that '&' is represent as &amp; in HTML and therefore, the logical, n+1 as start param will give 'a' as the result for spanLetter */
   var restString = m.substr(n+6, n.length);  
   alert(n);  
   alert('<span>' + spanLetter + '<span>');  
   alert(restString);  
});  

答案 4 :(得分:1)

尝试按照:

$(function(){
  $('ul>li:contains(&)').each(function(){
    var text = $(this).text();
    text = text.replace(/^&(\w){1}/, "<span>$1</span>");
    $(this).html(text);
  });
});

您可以看到示例here

答案 5 :(得分:1)

这个怎么样?

function() {
        $("li").each(
            function() {
                $(this).html($(this).text().replace(/&(.)/, '<span>$1</span>'));
            }
        );
    }
相关问题