Regex to format price - javascript

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.

Related

regex custom lenght but no whitespace allowed [duplicate]

I have a username field in my form. I want to not allow spaces anywhere in the string. I have used this regex:
var regexp = /^\S/;
This works for me if there are spaces between the characters. That is if username is ABC DEF. It doesn't work if a space is in the beginning, e.g. <space><space>ABC. What should the regex be?
While you have specified the start anchor and the first letter, you have not done anything for the rest of the string. You seem to want repetition of that character class until the end of the string:
var regexp = /^\S*$/; // a string consisting only of non-whitespaces
Use + plus sign (Match one or more of the previous items),
var regexp = /^\S+$/
If you're using some plugin which takes string and use construct Regex to create Regex Object i:e new RegExp()
Than Below string will work
'^\\S*$'
It's same regex #Bergi mentioned just the string version for new RegExp constructor
This will help to find the spaces in the beginning, middle and ending:
var regexp = /\s/g
This one will only match the input field or string if there are no spaces. If there are any spaces, it will not match at all.
/^([A-z0-9!##$%^&*().,<>{}[\]<>?_=+\-|;:\'\"\/])*[^\s]\1*$/
Matches from the beginning of the line to the end. Accepts alphanumeric characters, numbers, and most special characters.
If you want just alphanumeric characters then change what is in the [] like so:
/^([A-z])*[^\s]\1*$/

regex and replace string

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

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

regexp problem, the dot selects all text

I use some jquery to highlight search results. For some reason if i enter a basis dot, all of the text get selected. I use regex and replace to wrap the results in a tag to give the found matches a color.
the code that i use
var pattern = new.RegExp('('+$.unique(text.split(" ")).join("|")+")","gi");
how can i prevent that the dot selects all text, so i want to leave the point out of the code(the dot has no power)
You may be able to get there by doing this:
var pattern = new.RegExp('('+$.unique(text.replace('.', '\\.').split(" ")).join("|")+")","gi");
The idea here is that you're attempting to escape the period, which acts as a wild card in regex.
This will replace all special RegExp characters (except for | since you're using that to join the terms) with their escaped version so you won't get unwanted matches or syntax errors:
var str = $.unique(text.split(" ")).join("|"),
pattern;
str = str.replace(/[\\\.\+\*\?\^\$\[\]\(\)\{\}\/\'\#\:\!\=]/ig, "\\$&");
pattern = new RegExp('('+str+')', 'gi');
The dot is supposed to match all text (almost everything, really). If you want to match a period, you can just escape it as \..
If you have a period in your RegExp it's supposed to match any character besides newline characters. If you don't want that functionality you need to escape the period.
Example RegExp with period escaped /word\./
You need to escape the text you're putting into the regex, so that special characters don't have unwanted meanings. My code is based on some from phpjs.org:
var words = $.unique(text.split(" ")).join("|");
words = words.replace(/[.\\+*?\[\^\]$(){}=!<>|:\\-]/h, '\\$&'); // escape regex special chars
var pattern = new RegExp('(' + words + ")","gi");
This escapes the following characters: .\+*?[^]$(){}=!<>|:- with a backslash \ so you can safely insert them into your new RegExp construction.

Javascript split regex question

hello I am trying what I thought would be a rather easy regex in Javascript but is giving me lots of trouble.
I want the ability to split a date via javascript splitting either by a '-','.','/' and ' '.
var date = "02-25-2010";
var myregexp2 = new RegExp("-.");
dateArray = date.split(myregexp2);
What is the correct regex for this any and all help would be great.
You need the put the characters you wish to split on in a character class, which tells the regular expression engine "any of these characters is a match". For your purposes, this would look like:
date.split(/[.,\/ -]/)
Although dashes have special meaning in character classes as a range specifier (ie [a-z] means the same as [abcdefghijklmnopqrstuvwxyz]), if you put it as the last thing in the class it is taken to mean a literal dash and does not need to be escaped.
To explain why your pattern didn't work, /-./ tells the regular expression engine to match a literal dash character followed by any character (dots are wildcard characters in regular expressions). With "02-25-2010", it would split each time "-2" is encountered, because the dash matches and the dot matches "2".
or just (anything but numbers):
date.split(/\D/);
you could just use
date.split(/-/);
or
date.split('-');
Say your string is:
let str = `word1
word2;word3,word4,word5;word7
word8,word9;word10`;
You want to split the string by the following delimiters:
Colon
Semicolon
New line
You could split the string like this:
let rawElements = str.split(new RegExp('[,;\n]', 'g'));
Finally, you may need to trim the elements in the array:
let elements = rawElements.map(element => element.trim());
Then split it on anything but numbers:
date.split(/[^0-9]/);
or just use for date strings 2015-05-20 or 2015.05.20
date.split(/\.|-/);
try this instead
date.split(/\W+/)

Categories

Resources