String : Replace function with expression in Javascript - javascript

A string representing a currency is to be converted to a number.
For example:
Input : "125.632.454.454.403,51"
Output expected : 125632454454403.51
Currently I am trying:
Trial 1)
a = "125.632.454.454.403,51";
a.replace(/./, '');
Result = "25.632.454.454.403,51"
Trial 2)
a = "125.632.454.454.403,51";
a.replace(/./g, '');
Result = ""
But I expect the replace function to find all the occurrences of "." and replace by "".
Trial 3)
a = "125.632.454.454.403,51";
a.replace(/,/, '');
Result = "125.632.454.454.40351"
I would be glad if I find a fix for this.

You need to use \. instead of .. The dot (.) matches a single character, without caring what that character is. Also you can do it with single replace() with callback .
var str = "125.632.454.454.403,51";
str = str.replace(/\.|,/g, function(m) {
return m == '.' ? '' : '.'
});
document.write(str);

try:
var str = "125.632.454.454.403,51" ;
var result = str.replace(/\./g,'').replace(/\,/g,'.');
console.log(Number(result))

replace returns the changed string, it does not change it in-place!
You can find this out, by refering to the documentation.

Use
var Result = a.split('.').join("");
console.log(Result);

. has specific meaning in a regex. It matches any character. You need to escape the dot if you are actually looking for the character itself
var a = "125.632.454.454.403,51";
var result = a.replace(/\./g,"");

You can also do (parseFloat(a.replace(/[^0-9]+/g,""))/100)
And if you have to do this for multiple currencies, I would recommend looking into autonumeric.js. It handles all this for you.

Related

Regex - convert the string to camel caps by `dot`

I am looking for a solution to convert my string to camelcaps by the dot it contains.
here is my string: 'sender.state'
I am expecting the result as : 'senderState';
I tried this: 'sender.state'.replace(/\./g, ''); it removes the . but how to handle the camel caps stuff?
You can pass a function to .replace():
'sender.state'.replace(/\.([a-z])/g, (match, letter) => letter.toUpperCase());
Without regex - this might help :
var str = "bad.unicron";
var temp = str.split(".");
return temp[0]+temp[1].charAt(0).toUpperCase() + temp[1].slice(1);
I'll try to come up with regex

String.replace regex is not replacing `*` in string

I have a string that comes in and I am running a string.replace on it and it is not removing the * character from the string but it is removing the | character.
var s = "|*55.6";
s = s.replace(/[^0-9.]/, "");
console.log(s);
Use a global regular expression (/.../g) if you want to replace more than a single match:
s = s.replace(/[^0-9.]+/g, "") //=> "55.6"
Edit: Following your pattern with + (which matches more than one of a pattern in succession) will produce fewer matches and thus make the replacement with "" run more efficiently than using the g flag alone. I would use them both together. Credit to Jai for using this technique in his answer before me.
Demo Snippet
var s = "|*55.6"
s = s.replace(/[^0-9.]+/g, "")
console.log(s) //=> "55.6"
It's because replace executed just once. Use g option to replace every match.
s = s.replace(/[^0-9.]/g, "");
You haven't used a global flag for your regex, that is why the first occurrence was replaced, than the operation ended.
var s = "|*55.6";
s = s.replace(/[^\d.]/g, "");
console.log(s);
Using + quantifier alone wouldn't help if you have separate occurrences of [^\d.], though would be better to use together with g flag. For example;
var s = "|*55.6a"
s = s.replace(/[^0-9.]+/, "")
console.log(s) //=> "55.6a not OK
You need to use a global (g) flag / modifier or a plus (+) quantifier when replacing the string;
var s = "|*55.6";
s = s.replace(/[^0-9.]/g, "");
console.log(s);
var s = "|*55.6";
s = s.replace(/[^0-9.]+/, "");
console.log(s);
You are missing + to look for one or more occurrences:
var s = "|*55.6";
s = s.replace(/[^0-9.]+/, "");
console.log(s);
Also if you are interested to takeout the numbers, then you can use .match() method:
var s = "|*55.6";
s = s.match(/[(0-9.)]+/g)[0];
console.log(s);
Some answer mentioned the Quantifiers +, but it will still only replace the first match:
console.log("|*45.6abc".replace(/[^0-9.]+/, ""))
If you need to remove all non-digital chars(except .), the modifier/flag g is still required
console.log("|*45.6,34d".replace(/[^0-9.]+/g, ""));

get particular strings from a text that separated by underscore

I am trying to get the particular strings from the text below :
var str = "001AN_LAST_BRANCH_HYB_1hhhhh5_PBTsd_JENKIN.bin";
From this i have to get the following strings: "LAST", "BRANCH" and "JENKIN".
I used the code below to get "JENKIN";
var result = str.substr(str.lastIndexOf("_") +1);
It will get the result "JENKIN.bin". I need only "JENKIN".
Also the input string str sometimes contains this ".bin" string.
with substring() function you can extract text you need with defining start and end position. You have already found the start position with str.lastIndexOf("_") +1 and adding end position with str.indexOf(".") to substring() function will give you the result you need.
var result = str.substring(str.lastIndexOf("_") +1,str.indexOf("."));
It depends on how predictable the pattern is. How about:
var parts = str.replace(/\..+/, '').split('_');
And then parts[0] is 001AN, parts[1] is LAST, etc
You can use String.prototype.split to split a string into an array by a given separator:
var str = '001AN_LAST_BRANCH_HYB_1hhhhh5_PBTsd_JENKIN.bin';
var parts = str.split('_');
// parts is ['001AN', 'LAST', 'BRANCH', 'HYB', '1hhhhh5', 'PBTsd', 'JENKIN.bin'];
document.body.innerText = parts[1] + ", " + parts[2] + " and " + parts[6].split('.')[0];
You could do that way:
var re = /^[^_]*_([^_]*)_([^_]*)_.*_([^.]*)\..*$/;
var str = "001AN_LAST_BRANCH_HYB_1hhhhh5_PBTsd_JENKIN.bin";
var matches = re.exec(str);
console.log(matches[1]); // LAST
console.log(matches[2]); // BRANCH
console.log(matches[3]); // JENKIN
This way you can reuse your RegExp anytime you want, and it can be used in other languages too.
Try using String.prototype.match() with RegExp /([A-Z])+(?=_B|_H|\.)/g to match any number of uppercase letters followed by "_B" , "_H" or "."
var str = "001AN_LAST_BRANCH_HYB_1hhhhh5_PBTsd_JENKIN.bin";
var res = str.match(/([A-Z])+(?=_B|_H|\.)/g);
console.log(res)
I don't know why you want to that, but this example would be helpful.
It will be better write what exactly you want.
str = '001AN_LAST_BRANCH_HYB_1hhhhh5_PBTsd_JENKIN.bin'
find = ['LAST', 'BRANCH', 'JENKINS']
found = []
for item in find:
if item in str:
found.append(item)
print found # ['LAST', 'BRANCH']

Javascript regex to replace "split"

I would like to use Javascript Regex instead of split.
Here is the example string:
var str = "123:foo";
The current method calls:
str.split(":")[1]
This will return "foo", but it raises an Error when given a bad string that doesn't have a :.
So this would raise an error:
var str = "fooblah";
In the case of "fooblah" I'd like to just return an empty string.
This should be pretty simple, but went looking for it, and couldn't figure it out. Thank you in advance.
Remove the part up to and including the colon (or the end of the string, if there's no colon):
"123:foo".replace(/.*?(:|$)/, '') // "foo"
"foobar" .replace(/.*?(:|$)/, '') // ""
How this regexp works:
.* Grab everything
? non-greedily
( until we come to
: a colon
| or
$ the end of the string
)
A regex won't help you. Your error likely arises from trying to use undefined later. Instead, check the length of the split first.
var arr = str.split(':');
if (arr.length < 2) {
// Do something to handle a bad string
} else {
var match = arr[1];
...
}
Here's what I've always used, with different variations; this is just a simple version of it:
function split(str, d) {
var op = "";
if(str.indexOf(d) > 0) {
op = str.split(d);
}
return(op);
}
Fairly simple, either returns an array or an empty string.
var str1 = "123:foo", str2 = "fooblah";
var res = function (s) {
return /:/.test(s) && s.replace(/.*(?=:):/, "") || ""
};
console.log(res(str1), res(str2))
Here is a solution using a single regex, with the part you want in the capturing group:
^[^:]*:([^:]+)

How to convert string from textbox into a number using javascript?

I have a textbox with input value of 20,466,000.00 . I want to return only the value of 20466000 without a comma and a decimal point. I tried the following :
// Get value
var nca_balance = $("#nca-balance").text();
var nca_amount = parseInt(nca_balance.replace(",", ""),10);
alert(nca_amount);
But it only returns the value of 20466 ? Why ? My expected result must be 20466000. Please help with my code. Thanks
How about this one:
parseInt("20,466,000.00".replace(/,/g, ""), 10)
Because replace is replacing the first comma by default use g as global option in replace regular expression /,/g like,
var nca_balance = $("#nca-balance").text();
var nca_amount = parseInt(nca_balance.replace(/,/g, ""),10);
alert(nca_amount);
var nca_balance = $("#nca-balance").text();
var nca_amount = parseInt(nca_balance.replace(/,/g, ""), 10);
alert(nca_amount);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="nca-balance">20,466,000.00<span>
You have to use regular expression instead of replace function because replace function will replace only first matching character.
nca_balance = "20,466,000.00";
var nca_amount = parseInt(nca_balance.replace(/,/g, ''));
alert(nca_amount);
Regular expression /,/g will replace all comma with your provided character globally.

Categories

Resources