jquery - 正则字符串替换字符前的单词

时间:2014-05-01 21:00:55

标签: jquery regex

之前我问过这个问题并且我标记了一个答案,但它只执行了我需要的部分内容。

我正在尝试在2个html标签之间选择一些文字。它应该是非常直接的,但我似乎无法弄明白。

HTML:

<article>
    width
    <span class="Punctuation">:</span> 
    80%
    <span class="Punctuation">;</span>
    height
    <span class="Punctuation">:</span> 
    80%
    <span class="Punctuation">;</span>
    background
    <span class="Punctuation">:</span> 
    grey
    <span class="Punctuation">;</span>
</article>

所以我试图选择单词Width和值80%并将每个单词存储在不同的元素中。 最终结果将是:

<article>
    <span class="Property">width</span>
    <span class="Punctuation">:</span> 
    <span class="Value">80%</span>
    <span class="Punctuation">;</span>
    <span class="Property">height</span>
    <span class="Punctuation">:</span> 
    <span class="Value">80%</span>
    <span class="Punctuation">;</span>
    <span class="Property">background</span>
    <span class="Punctuation">:</span> 
    <span class="Value">grey</span>
    <span class="Punctuation">;</span>
</article>

我无法使用.text(),因为它会选择文章中不在span父级中的所有纯文本,而我正在尝试添加span元素不同的课程。

我基本上正在寻找一种正则表达式来选择:字符之前的单词并将其包装在span父级中。然后我想对;字符做同样的事情。

有没有人知道如何做到这一点?

---编辑---

我尝试了一些表达方式,但因为我没有任何正则表达式的经验而且我发现很难绕过我的脑袋,所以我没有走得太远。

我试图选择以

开头的字符串
var str = $('.code').html();
var match = str.match( /^: / );
alert(match);

但这似乎不起作用。

var str = $('.code').html();
var match = str.match( /;$/ );
alert(match);

也不起作用。两者都返回null

1 个答案:

答案 0 :(得分:1)

试试这个:

// Selects all the (naked text)
var nodetypes = $('article').contents().filter(function() {
    return this.nodeType === 3;
}), txt = nodetypes.text(); // store the naked text

nodetypes.remove(); // removed the naked text from the actual DOM

$.trim(txt.replace(/\n/g, '')) // remove all newlines from text
.replace(/\s+/g, ',')          // replaced one or more spaces with ","
.split(',')                    // split the string into array ','
.forEach(function (e, x) {     // loop through all the array items "e" is value "x" is index
    if (x % 2 === 0) {         // if x is even add element before `.Punctuation' class
        $('article .Punctuation').eq(x).before('<span class="Property">' + e + '</span>');
    } else {                   // if x is not even add element before `.Punctuation' class
        $('article .Punctuation').eq(x).before('<span class="Value">' + e + '</span>');
    }
});

JSFIDDLE