regex and replace string - javascript

Im trying to format my value accepting only digits and also replacing comma by dot, but i cant figure replace the comma by dot.
Example:
"4,82 €".replace(/[^\d\,]/g, '')
Expeted Value:
4.82

Try this: '4,82 €'.replace(/[^0-9,]/g, '').replace(/,/g, '.');
Also, you don't need to escape a ,. It has no reserved meaning in regex

Try handling this through two separate expressions, one to remove and the other to perform your replacement :
Remove all non digits and commas.
Replace all commas with periods.
This might look something like the expression below :
// Replaces all non-digits and commas /[^\d,]/ and replaces commas /,/
input.replace(/[^\d,]/g, '').replace(/,/g,'.`');
Example
// Replace any non-digit or commas and then replace commas with periods
console.log("4,82 € -> " + "4,82 €".replace(/[^\d\,]/g, '').replace(/,/g,'.'))
// If you want to allow periods initially, then don't remove them
console.log("4.82 € -> " + "4.82 €".replace(/[^\d\,.]/g, '').replace(/,/g,'.'))

You are almost right, just missed one small thing.
Your regex
[^\d\,]
will replace only one non-digit or comma character and not all.
Change your regex to
[^\d\,]+
like this
"4,82 €".replace(/[^\d\,]+/g, '')
and it will work

Related

Replace comma as separator

I am trying to build a Regex to replace commas used as a separator in between normal text.
Different ways I can replace that is valid:
Space before comma
Comma is between text and/or numbers, without any space
Several commas after each other
Example:
"This is a text separated with comma, that I try to fix. , It can be split in several ways.,1234321 , I try to make all the examples in one string,,4321,"
Results:
This is a text separated with comma, that I try to fix.
It can be split in several ways.
1234321
I try to make all the examples in one string
4321
This is the code I have so far using Node.js / Javascript:
data.replace(/(\S,\S)|( ,)|(,,)|(,([a-z0-9]))/ig,';')
The answer from #torazaburo work best, except for several commas with space in-between (, , , ,)
console.log(str.split(/ +, *|,(?=\w|,|$)/));
var str = "This is a text separated with comma, that I try to fix. , It can be split in several ways.,1234321 , I try to make all the examples in one string,,4321,";
console.log(str.split(/ +, *|,(?=\w|,|$)/));
This will split on any comma preceded by one or more spaces, no matter what follows (and eat the preceding spaces, and following spaces if any); or, any comma followed by an alphanumeric or comma or end-of-string.
There is no easy way with the regexp to get rid of the final empty string in the result, caused by the comma at the very end of the input. You can get rid of that yourself if you don't want it.
To rejoin with semi-colon, add .join(';').
data.replace(/\s*,+\s*/g, ';');
This will yield:
This is a text separated with comma;that I try to fix.;It can be split in several ways.;1234321;I try to make all the examples in one string;4321;
There are three parts to this:
\s*: Match zero or more whitespace characters.
,+: Match one or more commas.
\s*: Match zero or more whitespace characters.
If, instead, you want to replace any number of consecutive commas with a single semi-colon:
data.replace(/,+/g, ';');
Honestly, I'm not sure I understood your requirements. If I did misunderstand, please provide the output string you're expecting.

RegEx to replace variable quantity of characters with single character

Given this string
var d = 'The;Quick;;Brown;Fox;;;;;;Jumps';
What RegEx would I need to convert to this string:
'The,Quick,Brown,Fox,Jumps'
I need to replace 1-n characters (e.g. ';') with a single character (e.g. ',').
And because I know that sometimes you like to know "what are you trying to accomplish??"
I need to condition a string list of values that can be separated with a combination of different methods:
'The , Quick \r\n Brown , \r\n Fox ,Jumps,'
My approach was to convert all known delimiters to a standard character (e..g ';') and then replace that with the final desired ', ' delimiter
as Josh Crozier says, you can use
d = d.replace(/;+/g, ',');
You can also to the whole thing in one operation with something like
d = d.replace(/[,; \r\n]+/g, ',');
The [,; \r\n]+ part will find groups that are made of commas, semicolons, spaces etc.. Then the replace will replace them all with a single comma. You can add any other characters you want to treat as delimiters in with the brackets.
EDIT: actually, it's probably better to use something like this. The \s will match any whitespace character.
d.replace(/[,;\s]+/g, ',');
This should do the trick:
d.replace(/[;]+/g, ',')
It just replaces all group of semicolons together for a comma

Regex to format price

I have some price tags like $23.47,-$50.00, $0.37, $113.57,$600,0456.00 and so on. I intend to remove dollar($),thousand separator(,) and also any white space.
For this purpose I am using regex as
(Sometext).replace(/^[, ]+|[, ]+$|[, ]+/g, "").replace('$',"").replace(/\s+/g, ' ');
Is there any better way to combine all this operations(remove thousand separator comma, remove dollar symbol, remove white space) with single replace?
Can you just use the regex OR operator? Something like this:
(Sometext).replace(/^[, ]+|[, ]+$|[, ]+|\$|\s+/g, "");
The | represent an OR in regex. I just placed the pipe between the three patterns you want to match, and used them within a single replace(). I also escaped the $ in dollar sign matching statement.
Based on this this answer try:
var price = "$23 . 47"
var simpleValue = price.match(/(\d+)/g).join("")
You can use something like
'$444,55,22.33'.replace(/[,\s$]/g, "");
You could target anything NOT what you want to keep.
So, a regex like: price.replace(/[^\d\.-]/g, '');
The ^ in the brackets tells it to match anything but the included characters.
The \d allows any numeric character.

Replace text containing number in js

I would like to use .replace() function in JS to replace all occurencies of string "{5}".
I had no problems with letters in brackets but numbers just dont work if I call:
mystring.replace(/{\5}/g,'replaced')
nothing happens. Please can you help me with right syntax?
It looks like you have a problem with escaping. I'm pretty sure \5 is a backreference. You should instead be escaping the curly braces and not the number.
'Something {5} another thing'.replace(/\{5\}/g, 'replaced');
// -> Something replaced another thing
Additional Note: Just in case you're looking for a generalized string formatting solution, check out this SO question with some truly awesome answers.
Is there a special reason you are preceding the number with a backslash? If your intention is to match against the string "{5}", "{" and "}" are the special characters that should be escaped, not the character "5" itself!
According to MDN:
A backslash that precedes a non-special character indicates that the next character is
special and is not to be interpreted literally. For example, a 'b' without a preceding '\' generally matches lowercase 'b's wherever they occur. But a '\b' by itself doesn't match any character; it forms the special word boundary character.
The following code would work:
var str = "foo{5}bar{5}";
var newStr = str.replace(/\{5\}/g, "_test_");
console.log(newStr); // logs "foo_test_bar_test_"
Try this:
mystring.replace(/\{5\}/g,'replaced');
You need to escape the curly brackets\{ and \}.
DEMO
http://jsfiddle.net/tuga/Gnsq3/

Need to change regex to accept trailing spaces

I have a regex that accepts payments and amounts below. Allows for formats with "$" "," and two decimal spaces. I need this regex to allow trailing spaces after the decimal places like so '$50.00 '
/^\$?[0-9 ][0-9\, ]*(\.\d{1,2})?$|^\$?[\.]([\d][\d])$/
Thoughts?
\s* will capture any whitespace, including tabs and newlines:
/^\$?[0-9 ][0-9\, ]*(\.\d{1,2})?$|^\$?[\.]([\d][\d])\s*$/
If you're just trying to validate dollar values, I would make it a little simpler (although I don't know your exact use case):
/^\$?[0-9,]+(\.\d{2})?\s*$/
Just adding a [ ]* to the end should do the trick:
/^\$?[0-9 ][0-9\, ]*(\.\d{1,2})?[ ]*$|^\$?[\.]([\d][\d])[ ]*$/
But you can simplify this by wrapping your alternatives in a group. Also note that you don't need to escape , or . inside a character class, and you don't need a character class at all if there is only character you want to match.
/^\$?(?:[0-9 ][0-9, ]*(\.\d{1,2})?|\.([\d][\d]))[ ]*$/

Categories

Resources