Why is it that this regex almost works to return an array of two strings that can be used as numbers, positive or negative, but the 2nd string has its negative sign dropped? I can think of workarounds for this using another line or two of code, but would really like to get the regex to do it right. Thanks in advance. (By the way, the idea here is that the string can be "123,321" or "12.3, 321" or "123 32.1" or any reasonable formatting of two reals or integers.)
s="-123.23, -456.0";
s.match(/^([+-]?\d*\.\d*)\W+([+-]?\d*.\d*)$/);
//-->["-123.23, -456.0", "-123.23", "456.0"]
Instead of trying to match the entire line, you might consider just matching the numbers ...
var r = "-123.23, -456.0".match(/[+-]?\d+(?:\.\d+)?/g);
console.log(r); //=> [ '-123.23', '-456.0' ]
Try: [^\w-]+ instead \W+
s = "-123.23, -456.0";
s.match(/^([+-]?\d*\.\d*)[^\w-]+([+-]?\d*.\d*)$/)
Related
How to make a format number like below in javascript, i try workit with some regex, but it's not working.
99.999.999.9.999.999
You could use a regular expression with positive lookahead for a special length to the end of the string.
var regex = /(?=(.{13}|.{10}|.{7}|.{6}|.{3})$)/g,
value = '999999999999999',
result = value.replace(regex, '.');
console.log(result);
(9999999999999).toString().split("").reverse().map((el,i)=>(i+1)%3==0?"."+el:el).reverse().join("");
Make a string array out of it, then start from behind and add a point after each third element, then create a String out of that.
http://jsbin.com/lepecoyedo/edit?console
Alternatively, with fixed , positions:
var num=(9999999999999).toString().split("").reverse();
[3,6,7].forEach((i,o)=>num.splice(o+i,0,"."));//positions 3,6,8 (or others) from behind
num=num.reverse().join("");
http://jsbin.com/xahopuhira/edit?console
I am trying to write a basic function that will allow me to add a space to UK postcodes where the spaces have been removed.
UK postcodes always have a space before the final digit of the postcode string.
Some examples with no spacing and with correct spacing:
CB30QB => CB3 0QB
N12NL => N1 2NL
OX144FB => OX14 4FB
To find the final digit in the string I am regex /\d(?=\D*$)/g and the Javascript I have in place currently is as follows:
// Set the Postcode
var postCode = "OX144FB";
// Find the index position of the final digit in the string (in this case '4')
var postcodeIndex = postCode.indexOf(postCode.match(/\d(?=\D*$)/g));
// Slice the final postcode at the index point, add a space and join back together.
var finalPostcode = [postCode.slice(0, postcodeIndex), ' ', postCode.slice(postcodeIndex)].join('');
return finalPostcode;
I am getting the following results when I change the set postcost:
CB30QB becomes CB3 0QB - Correct
N12NL becomes N1 2NL - Correct
CB249LQ becomes CB24 9LQ - Correct
OX144FB becomes OX1 44FB - Incorrect
OX145FB becomes OX14 5FB - Correct
It seems that the issue might be to do with having two digits of the same value as most other combinations seem to work.
Does anyone know how I can fix this?
I should use string.replace
string.replace(/^(.*)(\d)/, "$1 $2");
DEMO
You can use replace() with regex, you need to place space before 3 letters from the end
document.write('CB30QB'.replace(/^(.*)(.{3})$/,'$1 $2')+'<br>');
document.write('N12NL'.replace(/^(.*)(.{3})$/,'$1 $2')+'<br>');
document.write('CB249LQ'.replace(/^(.*)(.{3})$/,'$1 $2')+'<br>');
document.write('OX144FB'.replace(/^(.*)(.{3})$/,'$1 $2'));
As everyone else is answering, .replace() is easier. However, let me point what's wrong in the code.
The problem is you're using postCode.indexOf() to find the first occurence of what has been matched. In this case:
Text: OX144FB
Match: ^ match is correct: "4"
Text: OX144FB
IndexOf: ^ first occurence of "4"
To fix it, use the .index of the match object:
// Find the index position of the final digit in the string (in this case '4')
var postcodeIndex = postCode.match(/\d(?=\D*$)/g).index;
var postCode = "OX144FB";
return postCode.replace(/^(.*)(\d)(.*)/, "$1 $2$3");
Using the String.prototype.replace method is obviously the easiest way:
return postCode.replace(/(?=\d\D*$)/, ' ');
or using the greediness:
return postCode.replace(/^(.*)(?=\d)/, '$1 ');
Your previous code doesn't work because you are searching with indexOf the substring matched with the String.prototype.match() method (that is the last digit before the end). But if this digit is several times in the string, indexOf will return the position of the first occurrence.
As an aside, when you want to find the position of a match in a string, use the String.prototype.search() method that returns this position.
This is an old problem, but whilst Avinash Raj's solution works, it only works if all your postcodes are without spaces. If you have a mix, and you want to regularize them to having a single space, you can use this regex:
string.replace(/(\S*)\s*(\d)/, "$1 $2");
DEMO - it even works with more than one space!
In my HTML markup, there will be a series of elements with the following naming scheme:
name="[].timeEntries[].Time"
Between both sets of brackets, there will be numbers with at least one possibly two digits. I need to filter out the second set of digits.
Disclaimer: This is my first time getting to know regex.
This is my pattern so far:
var re = /\[\d{1,2}\].timeEntries\[(\d{1,2})\]\.Time/;
I am not sure if I should use the * or + character to indicate two possible digits.
Is replace() the right method for this?
Do I need to escape the period '.' ?
Any other tips you can offer are appreciated.
For example, if I come across an element with
name="[10].timeEntries[9].Time"
I would like to put just the 9 into a variable.
I am not sure if I should use the * or + character to indicate two possible digits.
Neither, use {1,2}
\[\d{1,2}\]\.timeEntries\[(\d{1,2})\]\.Time
Example
This indicates explicitly 1 or 2 digits.
Also, yes, you should escape the .'s
You can use it like this:
var re = /\[\d{1,2}\]\.timeEntries\[(\d{1,2})\]\.Time/;
var myNumber = "[0].timeEntries[47].Time".match(re)[1];
Now myNumber will contain 47.
One final word of warning, myNumber contains the string "47". If your intention is to use it as a number you'll need to either use parseInt or use +:
var myNumber = +"[0].timeEntries[47].Time".match(re)[1];
You're pretty close.
There are a lot of ways you could do this - especially depending on how solid the format of that text will be.
You could use replace:
var re = /\[\d+\]\.timeEntries\[([\d]+)\]\.Time/;
var digits = element_name.replace(re, '$1');
If you know it will always be the second set of digits, you could use match
You could also use indexOf and/or split and some other string functions... In some cases that can be faster (but I think in your case, the regex is fine and probably easier to follow)
Well, I'm pretty new on regex and in particular on JavaScript regexp.
I'm looking for making a regexp that match the hex color syntax (like #34ffa6)
Then I looked at the w3school page: Javascript RegExp Object
Then that's my regexp:
/^#[0-9a-f]{6}/i
It seems to work but, if I want it to match also the "short hex color syntax" form? (like #3fa), it's possible? I've tried using the character | but maybe I'm wrong with the syntax.
/^#[0-9a-f]{3,6}$/i
would match #abc, #abcd, #abcde, #abcdef
/^#([0-9a-f]{3}|[0-9a-f]{6})$/i
would match #abc and #abcdef but not #abcd
/^#([0-9a-f]{3}){1,2}$/i
would match #abc and #abcdef but not #abcd
/^#(?:[0-9a-f]{3}){1,2}$/i
would match #abc and #abcdef but not #abcd
Have a look at RegExp - MDN to learn more about regular expressions in javascript.
Try this :
/^#([0-9a-f]{6}|[0-9a-f]{3})$/i
[0-9a-f]{6} = 6 characters
[0-9a-f]{3} = 3 characters
$ = end
this should work
/#[0-9a-f]{6}|#[0-9a-f]{3}/gi
and for trying out regular expressions on the fly and learning it you can use this site
http://gskinner.com/RegExr/
You might want to incorporate 4 and 8 digit hex for #RGBA and #RRGGBBAA. I am doing this in a different setting where I'm using match() and split() to generate arrays. I could not get all the variations posted by #rodneyrehm to work with the g flag and match, but the first (and most verbose) solution works if I list the character count in high to low order: 8, 6, 4, 3.
let rx = /(?:#)[0-9a-f]{8}|(?:#)[0-9a-f]{6}|(?:#)[0-9a-f]{4}|(?:#)[0-9a-f]{3}/ig
let s = "123 #AA22CC 100% #12F abc #A2Cd #aa11cc44 test 236px";
let arr = s.match(rx); // arr == ["#AA22CC", "#12F", "#A2Cd", "#aa11cc44"]
The MDN docs say that (?:#) should forget "#", but it does not, and (?=#) simply fails. What am I misunderstanding?
My final goal is to include the other numeric values in the array returned from match(). I'm almost there...
The possible Hex Colors are -
Format
Example
#RGB
#F00
#RGBA
#F005
#RRGGBB
#FF7C00
#RRGGBBAA
#FF7C0016
Regexp to match color without alpha
let regex = /^#([A-F0-9]{3}|[A-F0-9]{6})$/i
Regexp to match color with alpha
let regex = /^#([A-F0-9]{3,4}|[A-F0-9]{6}|[A-F0-9]{8})$/i
I have the following code:
var x = "100.007"
x = String(parseFloat(x).toFixed(2));
return x
=> 100.01
This works awesomely just how I want it to work. I just want a tiny addition, which is something like:
var x = "100,007"
x.replace(",", ".")
x.replace
x = String(parseFloat(x).toFixed(2));
x.replace(".", ",")
return x
=> 100,01
However, this code will replace the first occurrence of the ",", where I want to catch the last one. Any help would be appreciated.
You can do it with a regular expression:
x = x.replace(/,([^,]*)$/, ".$1");
That regular expression matches a comma followed by any amount of text not including a comma. The replacement string is just a period followed by whatever it was that came after the original last comma. Other commas preceding it in the string won't be affected.
Now, if you're really converting numbers formatted in "European style" (for lack of a better term), you're also going to need to worry about the "." characters in places where a "U.S. style" number would have commas. I think you would probably just want to get rid of them:
x = x.replace(/\./g, '');
When you use the ".replace()" function on a string, you should understand that it returns the modified string. It does not modify the original string, however, so a statement like:
x.replace(/something/, "something else");
has no effect on the value of "x".
You can use a regexp. You want to replace the last ',', so the basic idea is to replace the ',' for which there's no ',' after.
x.replace(/,([^,]*)$/, ".$1");
Will return what you want :-).
You could do it using the lastIndexOf() function to find the last occurrence of the , and replace it.
The alternative is to use a regular expression with the end of line marker:
myOldString.replace(/,([^,]*)$/, ".$1");
You can use lastIndexOf to find the last occurence of ,. Then you can use slice to put the part before and after the , together with a . inbetween.
You don't need to worry about whether or not it's the last ".", because there is only one. JavaScript doesn't store numbers internally with comma or dot-delimited sets.