user319940
user319940

Reputation: 3317

jQuery appending classes to matched string/number combo

I'm trying to add classes to parts of a strung/number combination. What I mean by this is something like this:

myword22-30

myword would always be the same so it should match that directly, the numbers could be different and the hypen would always be there. I would like the outcome to be a final markup of something like:

<span class="word">myword</span><span class="num1">22</span><span class="divider">-</span><span class="num2">30</span>

Firstly is this possible? and is it efficient to do something like this with fairly large blocks of text in jQuery?

Upvotes: 1

Views: 69

Answers (2)

Arun P Johny
Arun P Johny

Reputation: 388326

Try

$('p').html(function(idx, content){
    return content.replace(/myword\d+-\d+/g, function(text){
        var numcount = 0;
        return text.replace(/([a-zA-Z]+|\d+|-)/g, function(val){
            if(/[a-zA-Z]/.test(val)){
                return '<span class="word">' + val + '</span>';
            } else if(/[\d+]/.test(val)){
                return '<span class="num' + ++numcount + '">' + val + '</span>';
            } else {
                return '<span class="divider">' + val + '</span>';
            }
        });
    })
});

Demo: Fiddle

Upvotes: 3

user2523798
user2523798

Reputation: 11

Is this what you mean ?

var $newClass = $(".word").text() + $(".num1").text() + '-' + $(".num2").text();

http://jsfiddle.net/pgbqg/

then you can add this class by using

http://api.jquery.com/addClass/

Upvotes: 1

Related Questions