Santiago
Santiago

Reputation: 2465

Remove last character in regex .replace

I'm trying to detect numbers followed by "." and then wrap them in a <span> without that last "."

So far, this is what I have:

$(".item_title").each(function(index) {
    var t = $(this).html().replace(/(^\d+\.)/g, "<span>$1</span>");  
    $(this).html(t);
});

But I end up with <span>5.</span> and I'm looking for <span>5</span>

Also, is the way I'm doing the regex replace correct and efficient?

Thanks!

Upvotes: 1

Views: 1230

Answers (2)

Stphane
Stphane

Reputation: 3476

If you want the dot to be removed then put it out of the parenthesis

"5. some text 80.".replace(/(\d+)\s*\./g, "<span>$1</span>"); // \s* is needed if numbers can be followed by spaces

Upvotes: 1

h2ooooooo
h2ooooooo

Reputation: 39550

You're probably looking for a positive lookahead such as ([0-9]+)(?=\.).

var t = $(this).html().replace(/([0-9]+)(?=\.)/g, "<span>$1</span>");  

Which will turn

This is my string. It is a nice string. I have a total of bananas 5. Yes. 5 bananas.

into

This is my string. It is a nice string. I have a total of bananas <span>5</span>. Yes. 5 bananas.

DEMO

or if you want the dot to disappear, just move it out of the group:

var t = $(this).html().replace(/(^\d+)\./g, "<span>$1</span>");  
//                                    ^^

Which would turn out string into the following (notice the dot is gone):

This is my string. It is a nice string. I have a total of bananas <span>5</span> Yes. 5 bananas.

Upvotes: 2

Related Questions