Regex Capture Character and Replace with another - javascript

Trying to replace the special characters preceded by digits with dot.
const time = "17:34:12:p. m.";
const output = time.replace(/\d+(.)/g, '.');
// Expected Output "17.34.12.p. m."
console.log(output);
I had wrote the regex which will capture any character preceded by digit/s. The output is replacing the digit too with the replacement. Can someone please help me to figure out the issue?

You can use
const time = "17:34:12:p. m.";
const output = time.replace(/(\d)[\W_]/g, '$1.');
console.log(output);
The time.replace(/(\d)[\W_]/g, '$1.') code will match and capture a digit into Group 1 and match any non-word or underscore chars, and the $1. replacement will put the digit back and replace : with ..
If you want to "subtract" whitespace pattern from [\W_], use (?:[^\w\s]|_).
Consider checking more special character patterns in Check for special characters in string.

You should look for non word(\w) and non spaces (\s) characters and replace them with dot.
You should use some live simulator for regular expressions. For example regex101: https://regex101.com/r/xIStHH/1
const time = "17:34:12:p. m.";
const output = time.replace(/[^\w\s]/g, '.');
// Expected Output "17.34.12.p. m."
console.log(output);

Related

Javascript print some characters after regex match

Input string is "F000668A - EED14F50 - 000EED1KFF0000000F03".
I want to print/save 4 characters after EED1. The number of EED1 can 1 or more.
In the above example, the expected result is => 4F50,KFF0.
My code:
var input = "F000668A - EED14F50 - 000EED1kFF0000000F03"
const string = input.toLowerCase().replace(/\s/g, '').replace(/(\r\n|\n|\r)/gm, ""); //Lowercase it, delete spaces and linebreaks.
string.match(/eed1/g).forEach((element) => {
console.log(element)
});
Result:
eed1
eed1
But when I try to print further characters then the script print only 1 item.
string.match(/eed1(.*)/g)
Result:
eed14f50-000eed1kff0000000f03
How can I get the requested info with regex? (or an other way)
Thank you in advance.
You can use
const input = "F000668A - EED14F50 - 000EED1kFF0000000F03";
const matches = input.replace(/\s/g, '').matchAll(/eed1([a-z0-9]{4})/ig);
console.log(Array.from(matches, m => m[1]));
Note:
You do not need to replace line breaks separately from other whitespaces, \s matches \n, \r, and the rest of vertical whitesapce
There is no need to lowercase the input, you can use /i flag to match in a case insensitive way
/eed1([a-z0-9]{4})/ig will match all occurrences of eed1 (case insensitively) and then capture four letters/digits, and matchAll will ensure the access to all the capturing group values (match() discarded them all as the regex was built with the g flag).
See the regex demo.

Handling Dash Character in Regular Expression for Filenames

I have a string which will be used to create a filename. The original string pattern may include a dash. Recently, the pattern has changed and I need to handle the regular expression to remove the dashes near the end or middle of the string but not those at the beginning of the string.
Regular Expression Pattern Rules/Requirements:
Replace all special characters with an underscore with some exceptions
Remove dashes not located at the beginning of the string
The dashes which need to be kept are typically between numeric values [0-9] and can appear any number of times in the string (i.e. "23-564-8 Testing - The - String" -> "23-564-8_testing_the_string")
The dashes which should be converted to underscores are typically between [a-zA-Z] characters (i.e. "Testing - The - String" -> "testing_the_string")
Examples of Potential Strings:
23-564-8 Testing the String -> Expected Output: 23-564-8_testing_the_string
Testing - The String -> Expected Output: testing_the_string
23-564-8 Testing - The - String -> Expected Output: 23-564-8_testing_the_string
Opinion: Personally, I'm not a fan of including dashes in filename but it is a requirement
Current Regexp Solution:
var str = "23-564-8 Testing the String";
str.replace(/[^a-zA-Z0-9-]/g, '_').replace(/__/g, '_');
Question: What is the best way to handle this case? My current solution leaves all dashes in the string.
You may use this regex with a negative lookahead:
/[^a-zA-Z0-9-]+|-(?!\d)/g
RegEx Details:
[^a-zA-Z0-9-]+: Match 1 or more of any character that is not hyphen or alphanumeric
|: OR
-(?!\d): Match hyphen if it is NOT immediately followed by a digit
Code:
const arr = [
'23-564-8 Testing the String',
'Testing - The String',
'-23-564-8 Testing - The - String'
]
const re = /[^a-zA-Z0-9-]+|-(?!\d)/g
var result = []
arr.forEach(el => {
result.push( el.replace(re, '_').replace(/_{2,}/g, '_') )
})
console.log( result )
The following Regex pattern can be used with a replacement string $1_ (see demo):
(\d+(?:-+\d+)+)?[\W\-_]+
The pattern consists of two parts:
(\d+(?:-+\d+)+)? captures numbers with allowed dashes into the Group1
[\W\-_]+ captures special characters to be replaced
The Group1 is required to prevent allowed dashes from being replaced. The $1 token in the replacement string ensures that this content of Group1 will be kept in the result.
This Regex pattern also handles the scenario of duplicate _ characters, so .replace(/__/g, '_') is no longer required. The code can be transformed to:
var str = "23-564-8 Testing the String";
var res = str.replace(/(\d+(?:-+\d+)+)?[\W\-_]+/g, "$1_");
console.log(res);

How to match regular expression In Javascript

I have string [FBWS-1] comes first than [FBWS-2]
In this string, I want to find all occurance of [FBWS-NUMBER]
I tried this :
var term = "[FBWS-1] comes first than [FBWS-2]";
alert(/^([[A-Z]-[0-9]])$/.test(term));
I want to get all the NUMBERS where [FBWS-NUMBER] string is matched.
But no success. I m new to regular expressions.
Can anyone help me please.
Note that ^([[A-Z]-[0-9]])$ matches start of a string (^), a [ or an uppercase ASCII letter (with [[A-Z]), -, an ASCII digit and a ] char at the end of the string. So,basically, strings like [-2] or Z-3].
You may use
/\[[A-Z]+-[0-9]+]/g
See the regex demo.
NOTE If you need to "hardcode" FBWS (to only match values like FBWS-123 and not ABC-3456), use it instead of [A-Z]+ in the pattern, /\[FBWS-[0-9]+]/g.
Details
\[ - a [ char
[A-Z]+ - one or more (due to + quantifier) uppercase ASCII letters
- - a hyphen
[0-9]+ - one or more (due to + quantifier) ASCII digits
] - a ] char.
The /g modifier used with String#match() returns all found matches.
JS demo:
var term = "[FBWS-1] comes first than [FBWS-2]";
console.log(term.match(/\[[A-Z]+-[0-9]+]/g));
You can use:
[\w+-\d]
var term = "[FBWS-1] comes first than [FBWS-2]";
alert(/[\w+-\d]/.test(term));
There are several reasons why your existing regex doesn't work.
You trying to match the beginning and ending of your string when you
actually want everything in between, don't use ^$
Your only trying to match one alpha character [A-Z] you need to make this greedy using the +
You can shorten [A-Z] and [0-9] by using the shorthands \w and \d. The brackets are generally unnecessary.
Note your code only returns a true false value (your using test) ATM it's unclear if this is what you want. You may want to use match with a global modifier (//g) instead of test to get a collection.
Here is an example using string.match(reg) to get all matches strings:
var term = "[FBWS-1] comes first than [FBWS-2]";
var reg1 = /\[[A-Z]+-[0-9]\]/g;
var reg2 = /\[FBWS-[0-9]\]/g;
var arr1 = term.match(reg1);
var arr2 = term.match(reg2)
console.log(arr1);
console.log(arr2);
Your regular expression /^([[A-Z]-[0-9]])$/ is wrong.
Give this regex a try, /\[FBWS-\d\]/g
remove the g if you only want to find 1 match, as g will find all similar matches
Edit: Someone mentioned that you want ["any combination"-"number"], hence if that's what you're looking for then this should work /\[[A-Z]+-\d\]/

JS String: Add whitespace between numbers and letters

i need a regular expression or any other method to add whitespaces between numbers and letters in a string.
Example:
"E2356" => "E 2356"
"E123-F456" => "E 123-F 456"
I already found a regular expression capable of it but it is not possible with Javascript:
(?<=[^0-9])(?=[0-9])
Thanks!
Instead of a look-behind, just match the non-digit:
[^0-9](?=[0-9])
And replace with "$& ".
The [^0-9] subpattern will match 1 character that is not a digit that can be referenced with $& (the whole matched text) in the replacement pattern. (?=[0-9]) lookahead will make sure there is a digit right after it.
See demo
var re = /[^0-9](?=[0-9])/g;
var str = 'E2356<br/>E123-F456';
var result = str.replace(re, '$& ');
document.write(result);
Match the two-character sequence of letter followed by number, with capture groups for both the letter and number, then use String#replace with the $1 and $2 placeholders to refer to the content of the capture groups, with a space in between.
str.replace(/([^0-9])([0-9])/g, '$1 $2')
^^$1^^ ^^$2^
The g flag ensures all occurrences are replaced, of course.
Use String#replace:
'E123-F456'.replace(/([A-Z])(\d)/g, '$1 $2')
// >>> "E 123-F 456"
$1 and $2 are the captured groups from the regex and are separated by a space. The expression assumes you only have uppercase characters. Remember to add the g flag to your expression to replace every occurrence.
You cannot format a string using regex.
Regex helps you validate that whether a certain string follow the language described by expression.
Regex helps you capture certain parts of the string in different variables and then format them as you want to get the desired output.
So I would suggest you do something like this :
var data = "E2304" ;
var regex = ([^0-9])([0-9]*)/g ;
data.replace(/regex, '$1 $2') ;
Try below code
var test = "E123-F456".match(/[a-zA-Z]+|[0-9]+/g);
console.log(test.join(' '));
fiddle http://jsfiddle.net/anandgh/h2g8cnha/

regex string replace

I am trying to do a basic string replace using a regex expression, but the answers I have found do not seem to help - they are directly answering each persons unique requirement with little or no explanation.
I am using str = str.replace(/[^a-z0-9+]/g, ''); at the moment. But what I would like to do is allow all alphanumeric characters (a-z and 0-9) and also the '-' character.
Could you please answer this and explain how you concatenate expressions.
This should work :
str = str.replace(/[^a-z0-9-]/g, '');
Everything between the indicates what your are looking for
/ is here to delimit your pattern so you have one to start and one to end
[] indicates the pattern your are looking for on one specific character
^ indicates that you want every character NOT corresponding to what follows
a-z matches any character between 'a' and 'z' included
0-9 matches any digit between '0' and '9' included (meaning any digit)
- the '-' character
g at the end is a special parameter saying that you do not want you regex to stop on the first character matching your pattern but to continue on the whole string
Then your expression is delimited by / before and after.
So here you say "every character not being a letter, a digit or a '-' will be removed from the string".
Just change + to -:
str = str.replace(/[^a-z0-9-]/g, "");
You can read it as:
[^ ]: match NOT from the set
[^a-z0-9-]: match if not a-z, 0-9 or -
/ /g: do global match
More information:
https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Regular_Expressions
Your character class (the part in the square brackets) is saying that you want to match anything except 0-9 and a-z and +. You aren't explicit about how many a-z or 0-9 you want to match, but I assume the + means you want to replace strings of at least one alphanumeric character. It should read instead:
str = str.replace(/[^-a-z0-9]+/g, "");
Also, if you need to match upper-case letters along with lower case, you should use:
str = str.replace(/[^-a-zA-Z0-9]+/g, "");
str = str.replace(/\W/g, "");
This will be a shorter form
We can use /[a-zA-Z]/g to select small letter and caps letter sting in the word or sentence and replace.
var str = 'MM-DD-yyyy'
var modifiedStr = str.replace(/[a-zA-Z]/g, '_')
console.log(modifiedStr)

Categories