Javascript regex to replace numbers in sequence - javascript

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'));

Related

Seperate Number and Letter in a String

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);

Regex non exclusive group

Do you how can I get this result with Regex? In literal words, I want each groups of successives vowels with the maximum of consonants surrounding them (backward or foreward).
Example :
input : alliibaba
outputs :
[all]
[lliib]
[bab]
[ba]
I tried :
[bcdfghjklmnpqrstvwxyz]*[aeiou]+[bcdfghjklmnpqrstvwxyz]*
but it returns distincts groups, so I don't know if it's possible with Regex...
Thanks you for any help.
You can put the part of the regex that you want to be made non-exclusive in a lookaround pattern so that it leaves that portion of the search buffer for the next match. Since your rule appears to be that vowels do not overlap between matches while the surrounding consonants can, you can group the consonants after vowels in a lookahead pattern, while putting vowels and any preceding consonants in another capture group, and then concatenate the 2 matching groups into a string for output:
var re = /([bcdfghjklmnpqrstvwxyz]*[aeiou]+)(?=([bcdfghjklmnpqrstvwxyz]*))/g;
var s = 'alliibaba';
var m;
do {
m = re.exec(s);
if (m)
console.log(m[1] + m[2])
} while (m);

regex match not outputting the adjacent matches javascript

i was experimenting on regex in javascript. Then i came across an issue such that let consider string str = "+d+a+", I was trying to output those characters in the string which are surrounded by +, I used str.match(/\+[a-z]\+/ig), so here what I'm expecting is ["+d+","+a+"], but what i got is just ["+d+"], "+a+" is not showing in the output. Why?
.match(/.../g) returns all non-overlapping matches. Your regex requires a + sign on each side. Given your target string:
+d+a+
^^^
^^^
Your matches would have to overlap in the middle in order to return "+a+".
You can use look-ahead and a manual loop to find overlapping matches:
var str = "+d+a+";
var re = /(?=(\+[a-z]\+))/g;
var matches = [], m;
while (m = re.exec(str)) {
matches.push(m[1]);
re.lastIndex++;
}
console.log(matches);
With regex, when a character gets consumed with a match, then it won't count for the next match.
For example, a regex like /aba/g wouldn't find 2 aba's in a string like "ababa".
Because the second "a" was already consumed.
However, that can be overcome by using a positive lookahead (?=...).
Because lookaheads just check what's behind without actually consuming it.
So a regex like /(ab)(?=(a))/g would return 2 capture groups with 'ab' and 'a' for each 'aba'.
But in this case it just needs to be followed by 1 fixed character '+'.
So it can be simplified, because you don't really need capture groups for this one.
Example snippet:
var str = "+a+b+c+";
var matches = str.match(/\+[a-z]+(?=\+)/g).map(function(m){return m + '+'});
console.log(matches);

Javascript regex to extract count at end of file

I am fairly new to regex and am in need of some help.
The end goal is to capture the final sequence of numbers before the period in a file name. For example, I want to extract the '04' from 'test687.09ew0_d04.jpg'. Another example would be the '787' from '039lksdkl3200dj787.jpg'.
This is my regex so far:
/([0-9]+)(?:\.[\s\S]+)$/
My understanding is that the ([0-9]+) matches any number of digits 1 through 9.
The (?:\.[\s\S]+) specifies that the digits must be followed by a dot and any number of characters, the ?: marking that it should not be captured, but used to match.
The $ at the end is meant to only match if the requirements are at the end of the string and nowhere else.
However, it is not working. The non-capture groups are returned in my matches, and the regex is not requiring that the match be at the end of the string.
You could use a negated character class such as [^.] to match all the non-. characters at the end of the file name, [^.]+$.
Then match the literal . character, \., and capture the previous digits, (\d+).
(\d+)\.[^.]+$
The expression above would capture 04 in the string test687.09ew0_d04.jpg - example here.
I want to extract the '04' from 'test687.09ew0_d04.jpg'.
The solution using String.prototype.match() function:
var getLastDigits = function(str){
var m = str.match(/(\d+)\.\w+$/);
return m[1];
};
console.log(getLastDigits('test687.09ew0_d04.jpg'));
console.log(getLastDigits('039lksdkl3200dj787.jpg'));
var regex = /(\d+)\.[^\.]*$/;
function check(){
var str = prompt("Filename example: ");
var m = str.match(regex);
if(m && m[1])
alert("Here you go: " + m[1]);
else
alert("Nothing matched!");
}
<button onclick="check()">TRY</button>

Regular expression with asterisk quantifier

This documentation states this about the asterisk quantifier:
Matches the preceding character 0 or more times.
It works in something like this:
var regex = /<[A-Za-z][A-Za-z0-9]*>/;
var str = "<html>";
console.log(str.match(regex));
The result of the above is : <html>
But when tried on the following code to get all the "r"s in the string below, it only returns the first "r". Why is this?
var regex = /r*/;
var str = "rodriguez";
console.log(str.match(regex));
Why, in the first example does it cause "the preceding" character/token to be repeated "0 or more times" but not in the second example?
var regex = /r*/;
var str = "rodriguez";
The regex engine will first try to match r in rodriguez from left to right and since there is a match, it consumes this match.
The regex engine then tries to match another r, but the next character is o, so it stops there.
Without the global flag g (used as so var regex = /r*/g;), the regex engine will stop looking for more matches once the regex is satisfied.
Try using:
var regex = /a*/;
var str = "cabbage";
The match will be an empty string, despite having as in the string! This is because at first, the regex engine tries to find a in cabbage from left to right, but the first character is c. Since this doesn't match, the regex tries to match 0 times. The regex is thus satisfied and the matching ends here.
It might be worth pointing out that * alone is greedy, which means it will first try to match as many as possible (the 'or more' part from the description) before trying to match 0 times.
To get all r from rodriguez, you will need the global flag as mentioned earlier:
var regex = /r*/g;
var str = "rodriguez";
You'll get all the r, plus all the empty strings inside, since * also matches 'nothing'.
Use global switch to match 1 or more r anywhere in the string:
var regex = /r+/g;
In your other regex:
var regex = /<[A-Za-z][A-Za-z0-9]*>/;
You're matching literal < followed by a letter followed by 0 or more letter or digits and it will perfectly match <html>
But if you have input as <foo>:<bar>:<abc> then it will just match <foo> not other segments. To match all segments you need to use /<[A-Za-z][A-Za-z0-9]*>/g with global switch.

Categories

Resources