Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
29
rated 0 times [  32] [ 3]  / answers: 1 / hits: 51947  / 11 Years ago, thu, june 6, 2013, 12:00:00

I found this snippet somewhere and it works like a charm:



var n = parseInt(e.find(span.favNum).text().replace(/./g, )) + 1;


If I do it in a similar way it doesn't work anymore.



I do the following:



<div id =test>6.987</div>
var test = $(#test);
var r = test.text().replace(/./g, );
console.log(wrong , r);


I know that I can replace it also like this:



var r = test.text().replace(., );


This works.



I would like to understand why the stolen snippet is working.
Any idea?



http://jsfiddle.net/nJZMf/3/



The original script is found here: http://wp-svbtle.themeskult.com/



You will find the snippet by viewing the source of index.html and searching for .replace.


More From » jquery

 Answers
12

The reason that the code in the page you linked to works, where yours doesn't, is that it's not the same regular expression. Here's what I found in that page (and similar code in several places)



r = n.text().replace( /,/g,  )


where r is a jQuery object.



Note that the regular expression has a , inside the //, not a . like the code you had trouble with.



Comma is not a special character in regular expressions, so it needs no special treatment. Period has a special meaning. As the other answers pointed out, it matches all characters, and you need to prefix it with if you want to match . only.



Also note that .replace() is not jQuery code, it's JavaScript.



jQuery's .text() method returns a JavaScript String value. So anything you do with that string - such as the .replace() call - is actually a JavaScript String method.



The distinction is important when you want to research a problem: a search for javascript string replace will get you better information than jquery replace.


[#77775] Wednesday, June 5, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
yulissamirandah

Total Points: 493
Total Questions: 115
Total Answers: 94

Location: Lebanon
Member since Sun, Aug 2, 2020
4 Years ago
yulissamirandah questions
Fri, Jun 17, 22, 00:00, 2 Years ago
Wed, Aug 26, 20, 00:00, 4 Years ago
Tue, Jan 28, 20, 00:00, 4 Years ago
Mon, Nov 11, 19, 00:00, 5 Years ago
;