简体   繁体   中英

RegEx issue in JavaScript Function - Not replacing anything

Plan A: it's such a simple function... it's ridiculous, really. I'm either totally misunderstanding how RegEx works with string replacement, or I'm making another stupid mistake that I just can't pinpoint.

    function returnFloat(str){
        console.log(str.replace(/$,)( /g,""));
    }

but when I call it:

    returnFloat("($ 51,453,042.21)")
    >>> ($ 51,453,042.21)

It's my understanding that my regular expression should remove all occurrences of the dollar sign, the comma, and the parentheses. I've read through at least 10 different posts of similar issues (most people had the regex as a string or an invalid regex, but I don't think that applies here) without any changes resolving my issues.

My plan B is ugly:

            str = str.replace("$", "");
            str = str.replace(",", "");
            str = str.replace(",", "");
            str = str.replace(" ", "");
            str = str.replace("(", "");
            str = str.replace(")", "");
            console.log(str);   

There are certain things in RegEx that are considered special regex characters, which include the characters $ , ( and ) . You need to escape them (and put them in a character set or bitwise or grouping) if you want to search for them exactly. Otherwise Your Regex makes no sense to an interpreter

 function toFloat(str){ return str.replace(/[\\$,\\(\\)]/g,''); } console.log(toFloat('($1,234,567.90')); 

Please note that this does not conver this string to a float, if you tried to do toFloat('($1,234,567.90)')+10 you would get '1234568.9010'. You would need to call the parseFloat() function.

$字符表示行尾,请尝试:

console.log(str.replace(/[\$,)( ]/g,""));

You can fix your replacement as .replace(/[$,)( ]/g, "") .

However, if you want to remove all letters that are not digit or dot, and easier way exists:

.replace(/[^\d.]/g, "")

Here \\d means digit (0 .. 9), and [^\\d.] means "not any of the symbols within the [...] ", in this case not a digit and not a dot.

if i understand correctly you want to have this list : 51,453,042.21

What you need are character classes. In that, you've only to worry about the ], \\ and - characters (and ^ if you're placing it straight after the beginning of the character class "[" ). Syntax: [characters] where characters is a list with characters to be drop( in your case $() ).
The g means Global, and causes the replace call to replace all matches, not just the first one.

var myString = '($ 51,453,042.21)';
console.log(myString.replace(/[$()]/g, "")); //51,453,042.21

if you want to delete ','

var myString = '($ 51,453,042.21)';
console.log(myString.replace(/[$(),]/g, "")); //51453042.21

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM