Strip all non-numeric characters from string in JavaScript - 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

Related

Change a unique Character on jQuery

<span class="number1">10.00</span>
simply, i want to replace the '.'(dot) for a ','(comma) using jQuery.
I've tried several forms to search the $('.number1') characters and replacing
it with a comma.
<span class="number1">10.00</span>
What if there is more than one Dot in the string?
Why use jQuery for such a simple operation? What you need is a simple string manipulation. Adding a library so that you can type a few less characters to do something so basic seems hardly worth it.
What you really need the the plain old JavaScript String.replace() method.
Here's jQuery and non-jQuery ways to do it:
// With jQuery:
console.log($(".number1").text().replace(".", ","));
// Without jQuery:
console.log(document.querySelector(".number1").textContent.replace(".", ","));
// When you need to replace all the . chars. in the string, you'll need to use
// a regular expression with .replace().
// The / / denote the delimiters of a regular expression
// The \. is the escape code for a .
// The g means do a global find/replace throughout the string
// With jQuery:
console.log($(".number1").text().replace(/\./g, ","));
// Without jQuery:
console.log(document.querySelector(".number1").textContent.replace(/\./g, ","));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="number1">10.00.00</span>
Try this answer.
$(".number1").text(function () {
return $(this).text().replace(/\./g, ",");
});
this is a solution in vanilla js:
let spanNumber = document.querySelector('.number1')
let number = spanNumber.textContent
let newNumber = number.split('.').join(',')
spanNumber.innerHTML = newNumber
short version with replace:
let DOMElement = document.querySelector('.number1')
let string = DOMElement.textContent.replace('.',',')
DOMElement.innerHTML = string
Just use built in DOM property innerHTML, instead of unecessary jQuery mambo jambo like:
var num1 = document.querySelector('.number1');
num1.innerHTML = num1.innerHTML.replace('.', ',');
InnerHTML is value between your HTML tags, and since its a string it has access to all String prototype methods and properties.
Just turn it to array by finding a dot delimiter with split method, then get it right back using join like:
// Lets say that the value is 10.05.53.324.343
var num1 = document.querySelector('.number1');
num1.innerHTML = num1.innerHTML.split('.').join(','); // Outputs 10,05,53,324,343
You could use the Intl.NumberFormat object instead of replacing characters:
Perhaps you have other numbers on your content that you want to format.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat
But you can check a working example below that formats a number on US-EN format to pt-BR:
var el = document.querySelector('.number1');
var value = parseFloat(el.textContent);
var newValue = new Intl.NumberFormat('pt-BR', { minimumFractionDigits: 2 }).format(value);
el.innerHTML = newValue;
<span class="number1">10.00</span>

RegExp to filter characters after the last dot

For example, I have a string "esolri.gbn43sh.earbnf", and I want to remove every character after the last dot(i.e. "esolri.gbn43sh"). How can I do so with regular expression?
I could of course use non-RegExp way to do it, for example:
"esolri.gbn43sh.earbnf".slice("esolri.gbn43sh.earbnf".lastIndexOf(".")+1);
But I want a regular expression.
I tried /\..*?/, but that remove the first dot instead.
I am using Javascript. Any help is much appreciated.
I would use standard js rather than regex for this one, as it will be easier for others to understand your code
var str = 'esolri.gbn43sh.earbnf'
console.log(
str.slice(str.lastIndexOf('.') + 1)
)
Pattern Matching
Match a dot followed by non-dots until the end of string
let re = /\.[^.]*$/;
Use this with String.prototype.replace to achieve the desired output
'foo.bar.baz'.replace(re, ''); // 'foo.bar'
Other choices
You may find it is more efficient to do a simple substring search for the last . and then use a string slicing method on this index.
let str = 'foo.bar.baz',
i = str.lastIndexOf('.');
if (i !== -1) // i = -1 means no match
str = str.slice(0, i); // "foo.bar"

How to replace all the zeros in javascript

How can I replace all the zeroes with asterisks in a string?
I've tried:
var a = "00000004567";
a.replace(/0*\d/g,'*');
The problem is that it returns: "****567", which is undesirable.
var a = '00000004567';
a.replace(/0/g, '*');
Remove the *\d to convert all the zeroes to asterisks. The g modifier will handle the rest.
var a = "00000004567";
console.log(a.replace(/0/g, '*'))
Assuming you're talking about a string, use the global modifier like this:
a.replace(/0/g,"*");

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

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

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

Categories

Resources