Seperate Number and Letter in a String - javascript

let input_string='L10M111.05K268.68V 265.42';
let output_string='L 10 M 111.05 K 268.68 V 265.42';
Input string above has both numbers and letters in it which I need to seperate them using space as shown in my output string.
May I know how to achieve this? Any help will be very appreciated :)

One way to do it is to search the string for words (sequential letters) and numbers (digits, followed by an optional period and more digits), and ignore everything else. Then, with those matches, join them all on a single space. You can do that with:
'L10M111.05K268.68V 265.42'.match(/(\d+(\.\d+)?)|[a-zA-Z]+/g).join(' ')

use a regular expression with the replace method to insert spaces between the numbers and letters.
let input_string = 'L10M111.05K268.68V 265.42';
let output_string = input_string.replace(/([a-zA-Z])(\d)/g, '$1 $2');
console.log(output_string);

Here is a modified version that will also process negative numbers and numbers starting with a decimal point:
const res='abc.4L10M_D-111.05K268.68V 265.42 Last-.75end-it-all'.replace(/ *(-?(\.\d+|\d+(\.\d+)?)) */g," $1 ").trim();
console.log(res);

Related

Regex - How to replace a specific character in a string after being typed only once?

I'm trying to limit an input field to only numbers and the possibility of a "+" sign just at the string's [0] index. The idea is to let the user type their phone number, I have come up with this:
function main() {
let phone = document.getElementById('phone');
let phoneRegex = /[a-zA-Z]|[-!$%^&*()_|~=`{}[\]:";'<>?,./]/;
phone.value = phone.value.replace(phoneRegex, '');
console.log(phone.value);
}
<input id="phone">
<button onclick="main()">Run</button>
The thing is, this works fine, but I want to limit the first character to only a digit or a "+" sign, characters coming from index [1] and on should only be numbers.
I can't come up with an idea on how to solve this
Try this as a starting point (you'll probably want to expand it further to account for total string length, delimiters like -, etc.):
let phoneRegex = /\+?\d+/;
+ in a regular expression has a special meaning, so when we want to match the literal character "+" then we need to escape it. And following it with the ? character makes it optional:
\+?
Next, \d followed by + will match any sequence of one or more digits:
\d+
You can see a visualization of this pattern here.
I want to limit the first character to only a digit or a "+"
sign, characters coming from index [1] and on should only
be numbers.
The regex:
/^\+?\d+$/
means:
From the beginning, one or zero + signs, then one or more numbers until the end.
Note the following regex symbols:
* - zero or more
+ - one or more
? - zero or one
I know I'm late in this game, but adding one more solution for me and other's future references.
I came up with this solution which works for me:
/^(\+|[0-9])?[0-9]{12}$/
Thanks

Javascript regex to replace numbers in sequence

I am trying to replace numbers in string with the character "X" which works pretty good by replacing every individual number.
This the code:
let htmlStr = initialString.replace(/[0-9]/g, "X");
So in a case scenario that initialString = "p3d8" the output would be "pXdX"
The aim is to replace a sequence of numbers with a single "X" and not every number (in the sequence) individually. For example:
If initialString = "p348" , with the above code, the output would be "pXXX". How can I make it "pX" - set an "X" for the whole numbers sequence.
Is that doable through regex?
Any help would be welcome
Try
let htmlStr = "p348".replace(/[0-9]+/g, "X");
let htmlStr2 = "p348ad3344ddds".replace(/[0-9]+/g, "X");
let htmlStr3 = "p348abc64d".replace(/\d+/g, "X");
console.log("p348 =>",htmlStr);
console.log("p348ad3344ddds =>", htmlStr2);
console.log("p348abc64d =>", htmlStr3);
In regexp the \d is equivalent to [0-9], the plus + means that we match at least one digit (so we match whole consecutive digits sequence). More info here or regexp mechanism movie here.
You can use + after [0-9] It will match any number(not 0) of number. Check Quantifiers. for more info
let initialString = "p345";
let htmlStr = initialString.replace(/[0-9]+/g, "X");
console.log(htmlStr);
Use the \d token to match any digits combined with + to match one or more. Ending the regex with g, the global modifier, will make the regex look for all matches and not stop on the first match.
Here is a good online tool to work with regex.
const maskNumbers = str => str.replace(/\d+/g, 'X');
console.log(maskNumbers('abc123def4gh56'));

Match floats but not dates separated by dot

I'm trying to build a regex which can find floats (using a dot or comma as decimal separator) in a string. I ended up with the following:
/([0-9]+[.,]{1}[0-9]+)/g
Which seems to work fine expect that it matches dates separated by . as well:
02.01.2000 // Matches 12.34
I've tried ([0-9]+[.,]{1}[0-9]+)(?![.,]) but that does not work as I expected it :)
How would I omit the date case, but still pass the following scenarios:
I tried some stuff 12.23
D12.34
12.34USD
2.3%
12,2
\n12.1
You can use this regex using alternation:
(?:\d+\.){2}\d+|(\d+[.,]\d+)
and extract your matches from captured group #1.
This regex basically matches and discards date strings on LHS of alternation and then matches and captures floating numbers on RHS of alternation.
RegEx Demo
Code:
const regex = /(?:\d+\.){2}\d+|(\d+[.,]\d+)/gm;
const str = `I tried some stuff 12.23
D12.34
12.34USD 02.01.2000
2.3%
12,2 02.01.2000
\\n12.1`;
let m;
let results = [];
while ((m = regex.exec(str)) !== null) {
if (m[1])
results.push( m[1] );
}
console.log(results);
You want to make sure that it isn't surrounded with more ",." or numbers. Is that right?
/[^,.0-9]([0-9]+[.,]{1}[0-9]+)[^,.0-9]/g
Given the following:
hi 1.3$ is another 1.2.3
This is a date 02.01.2000
But this 5.30USD is a number.
But a number at the end of a sentance 1.7.
Or a number comma number in a list 4,3,4,5.
It will match "1.3" and "5.30"
Using #anubhava's example (?:\d+\.){2}\d+|(\d+[.,]\d+) You get the following result:
It will match "1.3", "5.30", "1.7", "4,3", and "4,5"
Moral of the story is you need to think through all the possible scenarios and understand how you want to treat each scenario. The last line should be a list of 4 numbers. But is "4,3" by itself two separate numbers or from a country where they use commas to denote decimal?

Regular expression for opposite of integer without leading zeros

I have a regex for integers with leading zero and it works fine. I am using it like:
value = value.replace(/[^0-9]/, '');
Now, I want another regex for integers without leading zero. So, I got the below mentioned regex from stackoverflow answer:
[1-9]+[0-9]*
As I am using string.replace, I have to invert the regex. So my final code looks like:
value = value.replace(/^(?![1-9]+[0-9]*)$/, '');
But now resulting value is always empty.
Expectations:
User should be allowed to typein these examples:
123456
123
78
User should not be able to type in these characters:
0123
e44
02565
asdf
02asf
754ads
Also, if I get a regex for only decimals without leading 0 and no e and should work in value.replace, then it will be a bonus for me.
I don't know how to construct regex patterns. So, if this a very basic question, then please forgive me.
Try
value = "e044".replace(/^.*?([1-9]+[0-9]*).*$/, '$1');
return 44
I would do it in two steps.
First remove the leading part (remove anything which is not a 1-9 at the beginning)
value = value.replace(/^[^1-9]*/, '');
then remove the trailing parts (match any number(s) in the beginning and remove the rest)
value = value.replace(/(?![0-9]+).*/, '');
for decimals use this (credits drkunibar):
value = value.replace(/.*?([1-9]+[0-9]*[\.]{0,1}[0-9]*).*/,'$1');
Please try this:
match = /^[1-9]\d*$/.test(value);
match will contain a boolean,true if the user enters a number without 0 in the lead,false-for anything other than number without 0 in the lead.

javascript match Regex for numbers and only dot character

I need to match Regex for an input text. It should allow only numbers and only one dot.
Below is my pattren.
(?!\s)[0-9\.\1]{0,}
This is allowing only numbers and allowing multiple dots. How to write so that it should allow only one dot?
Bascially when i enter decimal, i need to round off to whole number.
In case you dont mind accepting just a point, this should do it
\d*\.\d*
Otherwise, the more complete answer could look like this:
\d*\.\d+)|(\d+\.\d*)
You can use the following regex to select your integer and fractional parts than add 1 to your integer part depending to your fractional part:
Regex: ^(\d+)\.(\d+)$
In use:
function roundOff(str) {
return str.replace(/^(\d+)\.(\d+)$/g, ($0, $1, $2) => $2.split('')[0] >= 5 ? parseInt($1) + 1 : parseInt($2));
}
var str1 = roundOff('123.123')
console.log(str1); // 123
var str2 = roundOff('123.567')
console.log(str2); // 124

Categories

Resources