Jquery.replace (/./ g, "") doesn't work for me, but others

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 no longer works.

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 as follows:

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

It works.

I would like to understand why the "stolen" fragment works. Any idea?

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

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

You will find the snippet by looking at the index.html source and doing a .replace search.

+4
source share
5 answers

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

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

where r is a jQuery object.

Note that the regex has inside // , not a . like the code you came across.

A comma is not a special character in regular expressions, so it does not require special treatment. The period is of particular importance. As pointed out in other answers, it matches all characters, and you need to attach it to \ if you only want to . .

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

The jQuery .text() method returns a JavaScript String value. So, everything you do with this string, like calling .replace() , is actually a JavaScript String method.

The difference is important if you want to investigate the problem: looking for a "javascript string replacement" will help you get more accurate information than a "jquery replace".

+4
source

You need to get away from the "."

 test.text().replace(/\./g, ""); 
+5
source

It should be var r = test.text().replace(/\./g, ""); instead of var r = test.text().replace(/./g, ""); because you need to get out . so that it can be replaced.

+3
source

http://jsfiddle.net/mrk1989/nJZMf/4/

The solution is because I add \ to var r = test.text().replace(/\./g, "");

+2
source

The problem was that you did not escape the point.

But keep in mind that:

.replace(".", "");

.replace(/\./g, "");

- two different things.

For example: https://jsfiddle.net/rmhpkz9n/1/

0
source

Source: https://habr.com/ru/post/1484902/


All Articles