RegEx issue in JavaScript Function - Not replacing anything - javascript

Plan A: it's such a simple function... it's ridiculous, really. I'm either totally misunderstanding how RegEx works with string replacement, or I'm making another stupid mistake that I just can't pinpoint.
function returnFloat(str){
console.log(str.replace(/$,)( /g,""));
}
but when I call it:
returnFloat("($ 51,453,042.21)")
>>> ($ 51,453,042.21)
It's my understanding that my regular expression should remove all occurrences of the dollar sign, the comma, and the parentheses. I've read through at least 10 different posts of similar issues (most people had the regex as a string or an invalid regex, but I don't think that applies here) without any changes resolving my issues.
My plan B is ugly:
str = str.replace("$", "");
str = str.replace(",", "");
str = str.replace(",", "");
str = str.replace(" ", "");
str = str.replace("(", "");
str = str.replace(")", "");
console.log(str);

There are certain things in RegEx that are considered special regex characters, which include the characters $, ( and ). You need to escape them (and put them in a character set or bitwise or grouping) if you want to search for them exactly. Otherwise Your Regex makes no sense to an interpreter
function toFloat(str){
return str.replace(/[\$,\(\)]/g,'');
}
console.log(toFloat('($1,234,567.90'));
Please note that this does not conver this string to a float, if you tried to do toFloat('($1,234,567.90)')+10 you would get '1234568.9010'. You would need to call the parseFloat() function.

the $ character means end of line, try:
console.log(str.replace(/[\$,)( ]/g,""));

You can fix your replacement as .replace(/[$,)( ]/g, "").
However, if you want to remove all letters that are not digit or dot,
and easier way exists:
.replace(/[^\d.]/g, "")
Here \d means digit (0 .. 9),
and [^\d.] means "not any of the symbols within the [...]",
in this case not a digit and not a dot.

if i understand correctly you want to have this list : 51,453,042.21
What you need are character classes. In that, you've only to worry about the ], \ and - characters (and ^ if you're placing it straight after the beginning of the character class "[" ).
Syntax: [characters] where characters is a list with characters to be drop( in your case $() ).
The g means Global, and causes the replace call to replace all matches, not just the first one.
var myString = '($ 51,453,042.21)';
console.log(myString.replace(/[$()]/g, "")); //51,453,042.21
if you want to delete ','
var myString = '($ 51,453,042.21)';
console.log(myString.replace(/[$(),]/g, "")); //51453042.21

Related

Remove defined illegal characters from string

The chracters match if they are back to back. If the defined illegal characters are part of a long string, the correct sanitized text is not returned. The illegal characters that I want to find and replace with empty space is '-_+=[]{}\|'
I have read various regex blogs, Mozilla Developer Network site, as well as some answers here in stackoverflow. I have used \ for +, [, and |. If there is a more simple way, please, share it.
function dirtyString(str) {
cleanString = str.replace(/-_\+=\[]{}\|/g, "");
return cleanString;
}
For most of sample codes I have run, I don't get anything returned. I have run on Codepen and jsfiddle.
Put your characters into a character class (inside brackets)
A character class will math every character in it. For example, the regex /[abc]/g would match all of the a's, b's, and c's (the character class is [abc]. Also, the character class [a-zA-Z0-9] (which you might see a lot) matches all alphanumeric characters
Use a / before the brackets ([]). See more here.
var string = "s[s ass'-sas_+as[aasd]{ss}\asddfa|a]fasdf";
string = string.replace(/[ '-_+=\[\]{}\|]/g, '');
console.log(string);
Try putting your characters into a regex character class:
function dirtyString(str) {
cleanString = str.replace(/[\-_+=\[\]{}\\|]/g, "");
return cleanString;
}
var str = "HELLO-_+=[]{}|WORLD";
console.log(str);
console.log(dirtyString(str));
Note: You should escape square brackets and backslash even if inside a regex character class (not always true in every flavor of regex though).
You need to select them via a character class ([]);
function dirtyString(str) {
cleanString = str.replace(/[\-_+=\[\]{}\\|]/g, "");
return cleanString;
}
var string = "This -str_+in=g[ ]is {d}i|rty.";
console.log(dirtyString(string));

How to replace different characters with regex and add conditionals.

Example string: George's - super duper (Computer)
Wanted new string: georges-super-duper-computer
Current regex: .replace(/\s+|'|()/g, '-')
It does not work and and when I remove the spaces and there is already a - in between I get something like george's---super.
tl;dr Your regex is malformed. Also you can't conditionally remove ' and \s ( ) in a single expression.
Your regex is malformed since ( and ) have special meanings. They are used to form groups so you have to escape them as \( and \). You'll also have to place another pipe | in between them, otherwise you're going to match the literal "()", which is not what you want.
The proper expression would look like this: .replace(/\s+|'|\(|\)/g, '-').
However, this is not what you want. Since this would produce George-s---super-duper--Computer-. I would recommend that you use Character Classes, which will also make your expression easier to read:
.replace(/[\s'()-]+/g, '-')
This matches whitespace, ', (, ) and any additional - on or more times and replaces them with -, yielding George-s-super-duper-Computer-.
This is still not quite right, so have this:
var myString = "George's - super duper (Computer)";
var myOtherString = myString
// Remove non-whitespace, non-alphanumeric characters from the string (note: ^ inverses the character class)
// also trim any whitespace from the beginning and end of the string (so we don't end up with hyphens at the start and end of the string)
.replace(/^\s+|[^\s\w]+|\s+$/g, "")
// Replace the remaining whitespace with hyphens
.replace(/\s+/g, "-")
// Finally make all characters lower case
.toLowerCase();
console.log(myString, '=>', myOtherString);
You could do match instead of replace then join result on -. Then you may need a replace to remove single quotes. Regex would be:
[a-z]+('[a-z]+)*
JS code:
var str = "George's - super duper (Computer)";
console.log(
str.match(/[a-z]+('[a-z]+)*/gi).join('-').replace("'", "").toLowerCase()
);

Javascript: Remove trailing chars from string if they are non-numeric

I am passing codes to an API. These codes are alphanumeric, like this one: M84.534D
I just found out that the API does not use the trailing letters. In other words, the API is expecting M84.534, no letter D at the end.
The problem I am having is that the format is not the same for the codes.
I may have M84.534DAC, or M84.534.
What I need to accomplish before sending the code is to remove any non-numeric characters from the end of the code, so in the examples:
M84.534D -> I need to pass M84.534
M84.534DAC -> I also need to pass M84.534
Is there any function or regex that will do that?
Thank you in advance to all.
You can use the regex below. It will remove anything from the end of the string that is not a number
let code = 'M84.534DAC'
console.log(code.replace(/[^0-9]+?$/, ""));
[^0-9] matches anything that is not a numer
+? Will match between 1 and unlimited times
$ Will match the end of the string
So linked together, it will match any non numbers at the end of the string, and replace them with nothing.
You could use the following expression:
\D*$
As in:
var somestring = "M84.534D".replace(/\D*$/, '');
console.log(somestring);
Explanation:
\D stands for not \d, the star * means zero or more times (greedily) and the $ anchors the expression to the end of the string.
Given your limited data sample, this simple regular expression does the trick. You just replace the match with an empty string.
I've used document.write just so we can see the results. You use this whatever way you want.
var testData = [
'M84.534D',
'M84.534DAC'
]
regex = /\D+$/
testData.forEach((item) => {
var cleanValue = item.replace(regex, '')
document.write(cleanValue + '<br>')
})
RegEx breakdown:
\D = Anything that's not a digit
+ = One or more occurrences
$ = End of line/input

javascript replace all occurrences ",\S" with ", \S"

I want to have spaces separating items in a CSV string. That is "123,456,789" => "123, 456, 789". I have tried, but been unable to construct a regexp to do this. I read some postings and thought this would to the trick, but no dice.
text = text.replace(new RegExp(",\S", "g"), ", ");
Could anyone show me what I am doing wrong?
You have two problems:
Backslashes are a pain in the, um, backslash; because they have so many meanings (e.g. to let you put a quote-mark inside a string), you often end up needing to escape the backslash with another backslash, so you need ",\\S" instead of just ",\S".
The \S matches a character other than whitespace, so that character gets removed and replaced along with the comma. The easiest way to deal with that is to "capture" it (by putting it in parentheses), and put it back in again in the replacement (with $1).
So what you end up with is this:
text = text.replace(new RegExp(',(\\S)', "g"), ", $1");
However, there is a slightly neater way of writing this, because JavaScript lets you write a regex without having a string, by putting it between slashes. Conveniently, this doesn't need the backslash to be escaped, so this much shorter version works just as well:
text = text.replace(/,(\S)/g, ", $1");
As an alternative to capturing, you can use a "zero-width lookahead", which in this situation basically means "this bit has to be in the string, but don't count it as part of the match I'm replacing". To do that, you use (?=something); in this case, it's the \S that you want to "look ahead to", so it would be (?=\S), giving us this version:
text = text.replace(/,(?=\S)/g, ", ");
There are 2 mistakes in your code:
\S in a string literal translates to just S, because \S is not a valid escape sequence. As such, your regex becomes /,S/g, which doesn't match anything in your example. You can escape the backslash (",\\S") or use a regex literal (/,\S/g).
After this correction, you will replace the character following the comma with a space. For instance, 123,456,789 becomes 123, 56, 89. There are two ways to fix this:
Capture the non-space character and use it in the replacement expression:
text = text.replace(/,(\S)/g, ', $1')
Use a negative lookahead assertion (note: this also matches a comma at the end of the string):
text = text.replace(/,(?!\s)/g, ', ')
text = text.replace(/,(\S)/g, ', $1');
try this:
var x = "123,456,789";
x = x.replace(new RegExp (",", "gi"), ", ");

Replacing second part of string with Javascript and replace()

I need to replace any occurrence of a sequence of integers followed by a dash and then another sequence of integers, with only the first sequence of integers. For example:
THIS IS A STRING 2387263-1111 STRING CONTINUES
Will become:
THIS IS A STRING 2387263 STRING CONTINUES
Can I use that with Javascript and replace()?
You can do:
str = str.replace(/(\d+)-\d+/,'$1');
See it
Which replaces a group of digits followed by a hyphen followed by a group of digits with the first group of digits.
If you want to replace multiple occurrences of such pattern just use the g modifier as:
str = str.replace(/(\d+)-\d+/g,'$1');
NEW ANSWER -
Yes, in your case according to me, first you need to match that whole string "2387263-1111" using a regex and then remove that part followed by '-' and then replace the result in the original string.
Check the answer from codaddict. Mine would've almost been same but his answer seems more appropriate.
OLD ANSWER: -
Why replace? Just use split and get the first value.
var str = "2387263-1111";
var output = str.split("-")[0];
User RegExp function of javascript
str = str.replace(new RegExp("-[0-9]+"), " ");
Not really a new answer, just an addition to codaddict. Don't know JScript's regex
all that well, but I asume it uses extended regular expressions (if not, forget this).
If you need validation on boundry conditions you could do something like this:
str = str.replace( /((^|\s)\d+)-\d+(?=\s|$)/g, '$1' );
That would prevent matching this type of thing:
A STRING 2387263-1111STRING CONTINUES
A STRING2387263-1111 STRING CONTINUES
A STRING2387263-1111STRING CONTINUES

Categories

Resources