How to remove comma from number which comes dynamically in .tpl file - javascript

i want to remove comma from a number (e.g change 1,125 to 1125 ) in a .tpl file.
The value comes dynamically like ${variableMap[key]}

var a='1,125';
a=a.replace(/\,/g,''); // 1125, but a string, so convert it to number
a=parseInt(a,10);
Hope it helps.

var a='1,125'
a=a.replace(/\,/g,'')
a=Number(a)

You can use the below function. This function can also handle larger numbers like 123,123,123.
function removeCommas(str) {
while (str.search(",") >= 0) {
str = (str + "").replace(',', '');
}
return str;
};

var s = '1,125';
s = s.split(',').join('');
Hope that helps.

✨ ES2021 ✨ added replaceAll, so no need for regular expression:
const str = '1,125,100.05';
const number = parseFloat(str.replaceAll(",", ""));

You can use Regular Expression to change as it is faster than split join
var s = '1,125';
s = s.replace(/,/g, '');
//output 1125

Incoming value may not always be a string. If the incoming value is a numeric the replace method won't be available and you'll get an error.
Suggest using isNaN to see if numeric, then assume string and do replacement otherwise.
if(isNaN(x)) {
x = parseInt(x.replace(/[,]/g,''));
}
(Not foolproof because 'not number' doesn't prove it is a string, but unless you're doing something very weird should be good enough).
You can also add other symbols to the character group to remove other stray chars (such as currency symbols).

Related

How to split a string by a character not directly preceded by a character of the same type?

Let's say I have a string: "We.need..to...split.asap". What I would like to do is to split the string by the delimiter ., but I only wish to split by the first . and include any recurring .s in the succeeding token.
Expected output:
["We", "need", ".to", "..split", "asap"]
In other languages, I know that this is possible with a look-behind /(?<!\.)\./ but Javascript unfortunately does not support such a feature.
I am curious to see your answers to this question. Perhaps there is a clever use of look-aheads that presently evades me?
I was considering reversing the string, then re-reversing the tokens, but that seems like too much work for what I am after... plus controversy: How do you reverse a string in place in JavaScript?
Thanks for the help!
Here's a variation of the answer by guest271314 that handles more than two consecutive delimiters:
var text = "We.need.to...split.asap";
var re = /(\.*[^.]+)\./;
var items = text.split(re).filter(function(val) { return val.length > 0; });
It uses the detail that if the split expression includes a capture group, the captured items are included in the returned array. These capture groups are actually the only thing we are interested in; the tokens are all empty strings, which we filter out.
EDIT: Unfortunately there's perhaps one slight bug with this. If the text to be split starts with a delimiter, that will be included in the first token. If that's an issue, it can be remedied with:
var re = /(?:^|(\.*[^.]+))\./;
var items = text.split(re).filter(function(val) { return !!val; });
(I think this regex is ugly and would welcome an improvement.)
You can do this without any lookaheads:
var subject = "We.need.to....split.asap";
var regex = /\.?(\.*[^.]+)/g;
var matches, output = [];
while(matches = regex.exec(subject)) {
output.push(matches[1]);
}
document.write(JSON.stringify(output));
It seemed like it'd work in one line, as it did on https://regex101.com/r/cO1dP3/1, but had to be expanded in the code above because the /g option by default prevents capturing groups from returning with .match (i.e. the correct data was in the capturing groups, but we couldn't immediately access them without doing the above).
See: JavaScript Regex Global Match Groups
An alternative solution with the original one liner (plus one line) is:
document.write(JSON.stringify(
"We.need.to....split.asap".match(/\.?(\.*[^.]+)/g)
.map(function(s) { return s.replace(/^\./, ''); })
));
Take your pick!
Note: This answer can't handle more than 2 consecutive delimiters, since it was written according to the example in the revision 1 of the question, which was not very clear about such cases.
var text = "We.need.to..split.asap";
// split "." if followed by "."
var res = text.split(/\.(?=\.)/).map(function(val, key) {
// if `val[0]` does not begin with "." split "."
// else split "." if not followed by "."
return val[0] !== "." ? val.split(/\./) : val.split(/\.(?!.*\.)/)
});
// concat arrays `res[0]` , `res[1]`
res = res[0].concat(res[1]);
document.write(JSON.stringify(res));

extracting middle OR final part of a string

I want to extract only the first fontname out of a URL-string from the Google Webfont Directory. Here are some examples of possible strings and what part should be returned:
fonts.googleapis.com/css?family=Raleway // "Raleway"
fonts.googleapis.com/css?family=Caesar+Dressing // "Caesar Dressing"
fonts.googleapis.com/css?family=Raleway:300,400 // "Raleway"
fonts.googleapis.com/css?family=Raleway|Fondamento // "Raleway"
fonts.googleapis.com/css?family=Caesar+Dressing|Raleway:300,400|Fondamento // "Caesar Dressing"
So sometimes it's just one fontname, sometimes it has a weight indicated by a colon (:) and sometimes there are more fontnames divided by a pipe (|).
I have tried /family=(\S*)[:|]/ but it only matches the strings with :or |. I could do it like this, but it's not a nice solution:
var fontUrl = "fonts.googleapis.com/css?family=Caesar+Dressing|Raleway:300,400|Fondamento";
var fontName = /family=(\S*)/.exec(fontUrl)[1].replace(/\+/, " ");
if (fontName.indexOf(':') != -1){
fontName = fontName.split(':')[0];
}
if (fontName.indexOf('|') != -1){
fontName = fontName.split('|')[0];
}
console.log(fontName);
Is there a nice regex solution to this?
Instead of matching the character that (might) follow the string you want, match only the string you want except those characters:
/family=([^\s:|]*)/
Alternatively, you'd use a lookahead like this:
/family=(\S*?)(?=$|[:|])/
That should be better:
/family=([^:|]*)/
Of course for the + case, you'll have to replace it afterwards (or before maybe).
You can use (choose the i and m modifier in all case):
family=([a-z]+\+?[a-z]+)
or more simply
family=([a-z+]+)
or to avoid matching the + char:
family=([a-z]+)\+?([a-z]+)?
but it is an easyer way to use the second solution, and to replace the + chars with a space after.
try this:
/family\=(\S+?)[\:\|,]{0,2}\S*/ims
No regex is required in this case, unless you are good with regex's or test them thoroughly then you are likely to make mistakes.
var fontUrls = [];
fontUrls.push("fonts.googleapis.com/css?family=Raleway");
fontUrls.push("fonts.googleapis.com/css?family=Caesar+Dressing");
fontUrls.push("fonts.googleapis.com/css?family=Raleway:300,400");
fontUrls.push("fonts.googleapis.com/css?family=Raleway|Fondamento");
fontUrls.push("fonts.googleapis.com/css?family=Caesar+Dressing|Raleway:300,400|Fondamento");
function getFirstFont(url) {
return url.split("=")[1].split("|")[0].split(":")[0];
}
fontUrls.forEach(function (fontUrl) {
console.log(getFirstFont(fontUrl));
});
on jsfiddle

Javascript regex match for string "game_1"

I just can't get this thing to work in javascript. So, I have a text "game_1" without the quotes and now i want to get that number out of it and I tried this:
var idText = "game_1";
re = /game_(.*?)/;
found = idText.match(re);
var ajdi = found[1];
alert( ajdi );
But it doesn't work - please point out where am I going wrong.
If you're only matching a number, you may want to try
/game_([0-9]+)/
as your regular expression. That will match at least one number, which seems to be what you need. You entered a regexp that allows for 0 characters (*) and let it select the shortest possible result (?), which may be a problem (and match you 0 characters), depending on the regex engine.
If this is the complete text, then there is no need for regular expressions:
var id = +str.split('_')[1];
or
var id = +str.replace('game_', '');
(unary + is to convert the string to a number)
If you insist on regular expression, you have to anchor the expression:
/^game_(.*?)$/
or make the * greedy by omitting the ?:
/game_(.*)/
Better is to make the expression more restrictive as #Naltharial suggested.
Simple string manipulation:
var idText = "game_1",
adji = parseInt(idText.substring(5), 10);
* means zero or more occurrences. It seems that combining it with a greediness controller ? results in zero match.
You could replace * with + (which means one or more occurrences), but as #Felix Kling notes, it would only match one digit.
Better to ditch the ? completely.
http://jsfiddle.net/G8Qt7/2/
Try "game_1".replace(/^(game_)/, '')
this will return the number
You can simply use this re /\d+/ to get any number inside your string

Strip all non-numeric characters from string in JavaScript

Consider a non-DOM scenario where you'd want to remove all non-numeric characters from a string using JavaScript/ECMAScript. Any characters that are in range 0 - 9 should be kept.
var myString = 'abc123.8<blah>';
//desired output is 1238
How would you achieve this in plain JavaScript? Please remember this is a non-DOM scenario, so jQuery and other solutions involving browser and keypress events aren't suitable.
Use the string's .replace method with a regex of \D, which is a shorthand character class that matches all non-digits:
myString = myString.replace(/\D/g,'');
If you need this to leave the dot for float numbers, use this
var s = "-12345.50 €".replace(/[^\d.-]/g, ''); // gives "-12345.50"
Use a regular expression, if your script implementation supports them. Something like:
myString.replace(/[^0-9]/g, '');
You can use a RegExp to replace all the non-digit characters:
var myString = 'abc123.8<blah>';
myString = myString.replace(/[^\d]/g, ''); // 1238
Something along the lines of:
yourString = yourString.replace ( /[^0-9]/g, '' );
Short function to remove all non-numeric characters but keep the decimal (and return the number):
parseNum = str => +str.replace(/[^.\d]/g, '');
let str = 'a1b2c.d3e';
console.log(parseNum(str));
In Angular / Ionic / VueJS -- I just came up with a simple method of:
stripNaN(txt: any) {
return txt.toString().replace(/[^a-zA-Z0-9]/g, "");
}
Usage on the view:
<a [href]="'tel:'+stripNaN(single.meta['phone'])" [innerHTML]="stripNaN(single.meta['phone'])"></a>
The problem with these answers above, is that it assumes whole numbers. But if you need a floating point value, then the previous reg string will remove the decimal point.
To correct this you need write a negated character class with ^
var mystring = mystring.replace(/[^0-9.]/g, '');
try
myString.match(/\d/g).join``
var myString = 'abc123.8<blah>'
console.log( myString.match(/\d/g).join`` );
Unfortunately none of the answers above worked for me.
I was looking to convert currency numbers from strings like $123,232,122.11 (1232332122.11) or USD 123,122.892 (123122.892) or any currency like ₹ 98,79,112.50 (9879112.5) to give me a number output including the decimal pointer.
Had to make my own regex which looks something like this:
str = str.match(/\d|\./g).join('');
This,
.match(/\d|\.|\-/g).join('');
Handles both , and . also -
Example:
"Balance -$100,00.50".match(/\d|\.|\-/g).join('');
Outputs
10000.50
we are in 2017 now you can also use ES2016
var a = 'abc123.8<blah>';
console.log([...a].filter( e => isFinite(e)).join(''));
or
console.log([...'abc123.8<blah>'].filter( e => isFinite(e)).join(''));
The result is
1238

JavaScript match substring after RegExp

I have a string that look something like
something30-mr200
I would like to get everything after the mr (basically the # followed by mr) *always there is going to be the -mr
Any help will be appreciate it.
You can use a regexp like the one Bart gave you, but I suggest using match rather than replace, since in case a match is not found, the result is the entire string when using replace, while null when using match, which seems more logical. (as a general though).
Something like this would do the trick:
function getNumber(string) {
var matches = string.match(/-mr([0-9]+)/);
return matches[1];
}
console.log(getNumber("something30-mr200"));
var result = "something30-mr200".split("mr")[1];
or
var result = "something30-mr200".match(/mr(.*)/)[1];
Why not simply:
-mr(\d+)
Then getting the contents of the capture group?
What about:
function getNumber(input) { // rename with a meaningful name
var match = input.match(/^.*-mr(\d+)$/);
if (match) { // check if the input string matched the pattern
return match[1]; // get the capturing group
}
}
getNumber("something30-mr200"); // "200"
This may work for you:
// Perform the reg exp test
new RegExp(".*-mr(\d+)").test("something30-mr200");
// result will equal the value of the first subexpression
var result = RegExp.$1;
What about finding the position of -mr, then get the substring from there + 3?
It's not regex, but seems to work given your description?

Categories

Resources