Regex replace string which is not float - javascript

I have a string, where I need to parse it as a float, but first I need to replace it, if it is not a number (an integer or a float), so I am trying to create an regular expression to do it
My tries results in NaN
One of my best tries is
var $replace = $text.replace(/^[^d.]*/, '');
var $float = parseFloat($replace);
Can anybody tell me, what I am doing wrong?

If you really want to replace everything thats not a digit, then try this:
var $replace = $text.replace(/[^\d.]/g, '');
var $float = parseFloat($replace);
This will replace a string of "123a3d2" with a string of "12332".

It looks like you want to strip "non-numeric" characters from the beginning of the string before converting it to float. A naive approach would be:
var s = input.replace(/^[^\d.]+/, '');
var n = parseFloat(s);
This works for inputs like "foo123" but will fail on "foo.bar.123". To parse this we need a more sophisticated regexp:
var s = input.replace(/^(.(?!\d)|\D)+/, '');
var n = parseFloat(s);
Another method is to strip the input char by char until we find a valid float:
function findValidFloat(str) {
for (var i = 0; i < str.length; i++) {
var f = parseFloat(str.substr(i))
if (!isNaN(f))
return f;
}
return NaN;
}

if (! isNaN($text))
$float = parseFloat($text);
else
$float = 0; // or whatever

Related

Regular expression not capturing multiple characters [duplicate]

I have a string in JavaScript (e.g., #box2), and I just want the 2 from it.
I tried:
var thestring = $(this).attr('href');
var thenum = thestring.replace(/(^.+)(\w\d+\w)(.+$)/i, '$2');
alert(thenum);
It still returns #box2 in the alert. How can I get it to work?
It needs to accommodate for any length number attached on the end.
For this specific example,
var thenum = thestring.replace(/^\D+/g, ''); // Replace all leading non-digits with nothing
In the general case:
thenum = "foo3bar5".match(/\d+/)[0] // "3"
Here's a bonus: regex generator.
function getre(str, num) {
if(str === num)
return 'nice try';
var res = [/^\D+/g,/\D+$/g,/^\D+|\D+$/g,/\D+/g,/\D.*/g, /.*\D/g,/^\D+|\D.*$/g,/.*\D(?=\d)|\D+$/g];
for(var i = 0; i < res.length; i++)
if(str.replace(res[i], '') === num)
return 'num = str.replace(/' + res[i].source + '/g, "")';
return 'no idea';
};
function update() {
$ = function(x) { return document.getElementById(x) };
var re = getre($('str').value, $('num').value);
$('re').innerHTML = 'Numex speaks: <code>' + re + '</code>';
}
<p>Hi, I'm Numex, the Number Extractor Oracle.
<p>What is your string? <input id="str" value="42abc"></p>
<p>What number do you want to extract? <input id="num" value="42"></p>
<p><button onclick="update()">Insert Coin</button></p>
<p id="re"></p>
You should try the following:
var txt = "#div-name-1234-characteristic:561613213213";
var numb = txt.match(/\d/g);
numb = numb.join("");
alert (numb);​
Result
1234561613213213
I think this regular expression will serve your purpose:
var num = txt.replace(/[^0-9]/g, '');
Where txt is your string.
It basically rips off anything that is not a digit.
I think you can achieve the same thing by using this as well:
var num = txt.replace(/\D/g, '');
Try the following: string.replace(/[^0-9]/g, ''); This will delete all non-digit characters, leaving only digits in the string
function retnum(str) {
var num = str.replace(/[^0-9]/g, '');
return parseInt(num,10);
}
console.log('abca12bc45qw'.replace(/[^0-9]/g, ''));
console.log('#box2'.replace(/[^0-9]/g, ''));
Using the match function.
var thenum = "0a1bbb2".match(/\d+$/)[0];
console.log(thenum);
And this is a snippet which extracts prices with currency and formatting:
var price = "£1,739.12";
parseFloat(price.replace(/[^\d\.]*/g, '')); // 1739.12
I tried all the combinations cited in the previous answer with this code and got it working. It was the only one that worked on that string → (12) 3456-7890
var str = "(12) 3456-7890";
str.replace(/\D+/g, '');
Result: "1234567890"
Obs: I know that a string like that will not be on the attribute, but whatever, the solution is better, because it’s more complete.
You may use the great parseInt() method.
It will convert the leading digits to a number:
parseInt("-10px");
// Will give you -10
You can extract numbers from a string using a regex expression:
let string = "xxfdx25y93.34xxd73";
let res = string.replace(/\D/g, "");
console.log(res);
Output: 25933473
Wrap it into a vanilla JavaScript function:
function onlyNumbers(text){
return text.replace(/\D/g, "");
}
For a string such as #box2, this should work:
var thenum = thestring.replace(/^.*?(\d+).*/,'$1');
jsFiddle:
http://jsfiddle.net/dmeku/
function justNumbers(string)
{
var numsStr = string.replace(/[^0-9]/g, '');
return parseInt(numsStr);
}
console.log(justNumbers('abcdefg12hijklmnop'));
You can do a function like this
function justNumbers(string)
{
var numsStr = string.replace(/[^0-9]/g, '');
return parseInt(numsStr);
}
Remember: if the number has a zero in front of it, the int won’t have it
If you want to parse a number from a price like $6,694.20, it can be done this way:
parseFloat('$6,694.20'.replace(/^\D|,+/g, ''))
Or via a function:
function parsePrice(value) {
return parseFloat(value.replace(/^\D|,+/g, ''))
}
parsePrice('$6,694.20') // 6694.2
To return an int from the string, you can do the following code. It removes all not number characters and returns an integer.
Number("strin[g]3".replace(/\D+/g, ""))
You can use a regular expression.
var txt="some text 2";
var numb = txt.match(/\d/g);
alert (numb);
That will alert 2.
let str = "Total Work Duration: 189.56 Hrs.Present: 23.5 Absent: 2";
/* The provided regex globally matches the character
"." and a digit from the string */
let numArr = str.match(/[\d\.]+/g)
/* It returns an array [189.56, ., 23.5, 2], and
uses the filter function to remove the '.' */
numArr = numArr.filter(n => n != '.')
console.log(numArr)
If someone need to preserve dots in extracted numbers:
var some = '65,87 EUR';
var number = some.replace(",",".").replace(/[^0-9&.]/g,'');
console.log(number); // returns 65.87
You can use Underscore.js' string library as follows:
var common = "#box"
var href = "#box1"
_(href).strRight(common)
The result will be: 1
See: Underscore.string
Demo:
http://jsfiddle.net/abdennour/Vyqtt/
HTML code:
<p>
<a href="#box1" >img1</a>
<a href="#box2" >img2</a>
<a href="#box3" >img3</a>
<a href="#box4" >img4</a>
</p>
<div style="font-size:30px"></div>
JavaScript code:
var comm = "#box"
$('a').click(function() {
$('div').html(_($(this).attr('href')).strRight(comm))})
If you have a suffix as follows:
href="box1az"
You can use the following demo:
http://jsfiddle.net/abdennour/Vyqtt/1/
function retrieveNumber(all, prefix, suffix) {
var left = _(all).strRight(prefix);
return _(left).strLeft(suffix);
}
Here's a solution that checks for no data:
var someStr = 'abc'; // Add 123 to string to see the inverse
var thenum = someStr.match(/\d+/);
if (thenum != null)
{
console.log(thenum[0]);
}
else
{
console.log('Not a number');
}
var elValue = "-12,erer3 4,-990.234sdsd";
var isNegetive = false;
if(elValue.indexOf("-") == 0)
isNegetive = true;
elValue = elValue.replace( /[^\d\.]*/g, '');
elValue = isNaN(Number(elValue)) ? 0 : Number(elValue);
if(isNegetive)
elValue = 0 - elValue;
alert(elValue); // -1234990.234
With regular expressions, how to get numbers from a string, for example:
String myString = "my 2 first gifts were made by my 4 brothers";
myString = myString.replaceAll("\\D+", "");
System.out.println("myString: " + myString);
The result of myString is "24".
You can see an example of this running code at http://ideone.com/iOCf5G.
Use this one-line code to get the first number in a string without getting errors:
var myInt = parseInt(myString.replace(/^[^0-9]+/, ''), 10);
Please check the below JavaScript code. There you can get only a number.
var txt = "abc1234char5678#!9";
var str = txt.match(/\d+/g, "") + '';
var s = str.split(',').join('');
alert(Number(s));
Output: 1234567789
You need to add "(/\d+/g)" which will remove all non-number text, but it will still be a string at this point. If you create a variable and "parseInt" through the match, you can set the new variables to the array values. Here is an example of how I got it to work:
var color = $( this ).css( "background-color" );
var r = parseInt(color.match(/\d+/g)[0]);
var g = parseInt(color.match(/\d+/g)[1]);
var b = parseInt(color.match(/\d+/g)[2]);
This answer will cover most of the scenarios. I came across this situation when a user tried to copy paste the phone number.
$('#help_number').keyup(function() {
$(this).val().match(/\d+/g).join("")
});
Explanation:
str = "34%^gd 5-67 6-6ds"
str.match(/\d+/g)
It will give an array of strings as output:
["34", "56766"]
 
str.match(/\d+/g).join("")
join() will convert and concatenate that array data into a single string.
Output:
"3456766"
In my example, I needed the output as 209-356-6788, so I used replace():
$('#help_number').keyup(function() {
$(this).val($(this).val().match(/\d+/g).join("").replace(/(\d{3})\-?(\d{3})\-?(\d{4})/, '$1-$2-$3'))
});
Written without a regular expression:
// Without Regex
function extractNumber(string) {
let numArray = string.split('').map(item => {
if (typeof +item === 'number' && !isNaN(+item))
return +item
})
return +numArray.join('')
}
extractNumber('#1200milion$') // 1200
In one of my projects I had to take a rating value from a string. This is what I used:
let text = '#xbox2'
let num = text.trim().
split('').
map(num => Number(num)).
filter(x => Number.isInteger(x))
Use:
changeStrangeDate(dateString: string) {
var sum = 0;
var numbers = dateString.match(/\d+/g);
if (numbers.length > 1) {
numbers.forEach(element => {
sum += parseInt(element);
}
);
}
console.log(new Date(sum).toDateString());
return new Date(sum).toUTCString();
}
You can do it like that and then call a function where you need it, with a parameter.
this.changeStrangeDate('/Date(1551401820000-0100)/');

How to reverse a string using only one variable

How to reverse string using next conditions:
1) if string isn't parameter of function,
2) if string is place in global scope,
3) use loop like for, while,
4) can add one variable
Note: Can't use method .join, .split, .reverse and so on...
If it possible and not so hard for you make explain your solution, very grateful !
In other words, this is what you got:
let s = 'any string';
let p; // feel free to use at your discretion
// your code here. No further variables, no functions and no built-ins
// should console.log the reversed string
I'm understand that my solution is very close to my desire (conditions), but i can't generate other solution.
function convers(s){ //parameter
var str = "";//empty string for new converted string
for(var i = s.length-1; i >= 0; i--)//loop decremebtation that count from end of string
str+=s[i];//store result and assignments to str
return str;// declare result
}
console.log(convers("abcdef"));
I looked this source:
javascript reverse string algorithm
Is there a faster Reverse String Algorithm for JavaScript? - but it is useless for me, sorry.
I'm sorry if my explanation is not clear enough. Sorry for my English, I'm beginner here :))))
You could use a new variable for the reverted string and use the length property for iterating.
var string = 'abcdef',
reverse = '';
while (reverse.length !== string.length) {
reverse += string[string.length - 1 - reverse.length];
}
string = reverse;
console.log(string);
A bit shorter.
var string = 'abcdef',
reverse = '';
while (reverse.length !== string.length) {
reverse = string[reverse.length] + reverse;
}
string = reverse;
console.log(string);
Please check below condition I hope it will help you
1) if string isn't parameter of function
function convers(s){ //parameter
s = s.toString();
var str = "";//empty string for new converted string
for(var i = s.length-1; i >= 0; i--)//loop decremebtation that count from end of string
str+=s[i];//store result and assignments to str
return str;// declare result
}
console.log(convers(132));
2) if string is place in global scope
function convers(){ //parameter
var str = "";//empty string for new converted string
for(var i = dd.length-1; i >= 0; i--)//loop decremebtation that count from end of string
str+=dd[i];//store result and assignments to str
return str;// declare result
}
var dd ="123";
console.log(convers());
3) can add one variable
function convers(s,dd){ //parameter
var str = "";//empty string for new converted string
for(var i = s.length-1; i >= 0; i--)//loop decremebtation that count from end of string
str+=s[i];//store result and assignments to str
return str +dd;// declare result
}
function CallConvers(){
var dd = "ADD";
console.log(convers("abcdef",dd));
}
CallConvers();

How to split a string at commas but ignore \,?

I want to split string http://some.com/\,brabra,400,500 into ['http://some.com/\,brabra', 400, 500]
I already tried this, but error because lookbehind is not support in js.
'http://some.com/\,brabra,400,500'.split(/(?<!\\),/g)
Any other ideas to do this?
You may use matching approach with (?:[^,\\]+|\\.)+:
match(/(?:[^,\\]+|\\.)+/g)
See the regex demo
Details: the (?:[^,\\]+|\\.)+ matches 1 or more occurrences ((?:...)+) of a 1+ characters other than , and \ (with [^,\\]+) or (|) any escaped sequence (\\.)
var s = "http://some.com/\\,brabra,400,500"
console.log(s.match(/(?:[^,\\]+|\\.)+/g));
Or a workaround if the comma to be split with is always followed with a digit:
split(/,(?=\d)/)
See this regex demo
var s = "http://some.com/\\,brabra,400,500"
console.log(s.split(/,(?=\d)/));
A classic, if slightly inelegant approach for such problems is to replace some characters with a magic token, then put them back later:
str
.replace("\\,", "DONT_SPLIT_HERE")
.split(',')
.map(part => part.replace("DONT_SPLIT_HERE", "\\,")
you can use simulate positive lookaheads with reversing the string:
String.prototype.reverse = function() {
return this.split("").reverse().join("");
}
Array.prototype.reverseElements = function() {
var ar = [];
for (var i = 0; i < this.length; i++) {
if (typeof this[i] === 'string')
ar[i] = this[i].reverse();
else {
//Do something if not a String
}
}
return ar;
}
var str = "http://some.com/\,brabra,400,500";
var ar = str.reverse().split(/,(?!\\)/).reverse().reverseElements();
console.log(ar);
Note: The Regex works here, but not in the snippet.

Any javascript string function?

Some outside code is giving me a string value like..
null,402,2912,2909,2910,2913,2911,2914,2915,2388,2389,2390,
now i have to save this value to the data base but putting 0 in place of null in javascript. Is there any javascript string releated function to do this conversion?
You can simply use the replace function over and over again until all instances are replaced, but make sure that all your string will ever contain is the character sequence null or a number (and obviously the delimiting comma):
var str = "null,402,2912,null"
var index = str.indexOf("null");
while(index != -1) {
str = str.replace("null", "0");
index = str.indexOf("null");
}
You need to run a for loop because the function String.replace(search, rplc) will replace only the first instance of search with rplc. So we use the indexOf method to check, in each iteration, if the required term exists or not. Another alternative (and in my opinion, a better alternative would be:
var str = "null,402,2912,null"
var parts = str.split(",");
var data = []
for(var i=0; i<parts.length; i++) {
data[data.length] = parts[i]=="null"?0:parseInt(parts[i]);
}
Basically, what we are doing is that since you will anyways be converting this to an array of numbers (I presume, and sort of hope), we first split it into individual elements and then inspect each element to see if it is null and make the conversion accordingly.
This should answer your needs:
var str = 'null,402,2912,2909,2910,2913,2911,2914,2915,2388,2389,2390';
str.split(",").map(function (n) { var num = Number(n); return isNaN(num) ? 0 : num; });
The simplest solution is:
var inputString = new String("null,402,2912,2909,2910,2913,2911,2914,2915,2388,2389,2390,");
var outputString = inputString.replace("null", "0");
What I understood from your question is:
You want to replace null with 0 in a string.
You may use
string = "null,402,2912,2909,2910,2913,2911,2914,2915,2388,2389,2390,"
string.replace(/null/g,0)
Hope it helps.

Quick Problem - Extracting numbers from a string

I need to extract a single variable number from a string. The string always looks like this:
javascript:change(5);
with the variable being 5.
How can I isolate it? Many thanks in advance.
Here is one way, assuming the number is always surrounded by parentheses:
var str = 'javascript:change(5);';
var lastBit = str.split('(')[1];
var num = lastBit.split(')')[0];
Use regular expressions:-
var test = "javascript:change(5);"
var number = new RegExp("\\d+", "g")
var match = test.match(number);
alert(match);
A simple RegExp can solve this one:
var inputString = 'javascript:change(5);';
var results = /javascript:change\((\d+)\)/.exec(inputString);
if (results)
{
alert(results[1]); // 5
}
Using the javascript:change part in the match as well ensures that if the string isn't in the proper format, you wont get a value from the matches.
var str = 'javascript:change(5);', result = str.match(/\((\d+)\)/);
if ( result ) {
alert( result[1] )
}

Categories

Resources