Get number(decimal digit) from String - javascript

I see somebody already asked this question but the result is not really in the case of number is decimal digit.
Example:
var str = "textsometext13.523 after text";
Then if I use str.replace(/[^0-9]/gi, '');
It will return 13523 instead of 13.523
How I can use new regex to get it?
Thank you very much.

If you know your input string will only contain one number and not have a full stop at the end then simply update your regex to include a . in the list of characters to keep:
/[^0-9.]/gi
But if you need to allow for input like the following:
"text 123.12 text 13"
"The numbers are 132.12, 144.11, and 123.1."
...then you should use the .match() method, which with the right regex will return an array of matched numbers (or return null if there were no matches):
var results = input.match(/\d+(?:\.\d+)?/g);
That is, match one or more digits \d+, that are optionally followed by a decimal \. and one or more digits \d+.
Demo:
console.log( "text 123.12 text".match(/\d+(?:\.\d+)?/g) );
console.log( "The numbers are 132.12, 5, and 123.1.".match(/\d+(?:\.\d+)?/g) );
console.log( "No numbers".match(/\d+(?:\.\d+)?/g) );

You can use RegExp /\d+\.\d+|\d+/g to match digits followed by . character followed by digits, or one or more digits
str.match(/\d+\.\d+|\d+/g)

You can try this one:
var string = "textsometext13.523 after text";
var number = string.match(/[\d\.]+/).toString();
var num = number.split('.');
alert(num[1]); //display the numbers after the period(.) symbol

simply use like this /\d+(?:\.\d+)?/g:
console.log("textsometext13.523 after text".match(/\d+(?:\.\d+)?/g,""))
Alternate, its the reverse process replace the [a-z] same thing will append
console.log("textsometext13.523 after text".replace(/[a-z]/g,""))

This regex should match any number whether it has a decimal or not:
/(\d*\.?\d*)/g
SNIPPET
var btn1 = document.getElementById('btn1');
var inp1 = document.getElementById('inp1');
var out1 = document.getElementById('out1');
btn1.onclick = function() {
var str = inp1.value
var res = str.match(/\d*\.?\d*/g);
out1.innerHTML = res;
}
<input id='inp1'>
<input id='btn1' type='button' value='Extract Numbers'>
<output id='out1'></output>

Related

separate whole numbers and decimals from a string

I have a text string that can be as follows let str = '10x2.34' from which I would like to get only the numbers so try the following:
str.match(/\d+/g)
This ignores the characters and returns the numbers to me, but it only works for whole numbers, so how could I get the whole numbers and decimals, which can come in the following ways: let str = '10x2.34' or let str = '10x2,34'
Match digits with \d and punctuation with \. or , :
str.match(/[\d\.,]+/g)
const regex = /[\d\.,]+/g
console.log( "10x2.34".match(regex) ) // ["10","2.34"]
console.log( "10x2,34".match(regex) ) // ["10","2,34"]

How to write regular expression to filter out string with single occurence of 4 in , separated string array

In the below example I need to get the strings which have only 4 and not 44.
var strs = ["3,4,6","4,5,6","1,2,3,4","44,55","55,44","33,44,55"];
var patt = new RegExp(/[,|^\d]*4[,|^\d]*/);
for(i in strs){
var str = strs[i];
var res = patt.test(str);
if(res){
console.log(str);
}else{
console.error(str);
}
}
^(?!.*(\d4|4\d)).*4.*$
(?!.*(\d4|4\d)) it ensure that no string should not contain any digit contain 4 and greater than 10.
.*4.* ensure that string contain at least 1 "4".
Demo
Try
^(?!.*(\d4|4\d).*).*$
It uses a negative look-ahead to assert that there isn't a combination of 4 followed by a digit, or the other way around.
See it here at regex101.

Remove last comma (and possible whitespaces after the last comma) from the end of a string

Using JavaScript, how can I remove the last comma, but only if the comma is the last character or if there is only white space after the comma? This is my code.
I got a working fiddle. But it has a bug.
var str = 'This, is a test.';
alert( removeLastComma(str) ); // should remain unchanged
var str = 'This, is a test,';
alert( removeLastComma(str) ); // should remove the last comma
var str = 'This is a test, ';
alert( removeLastComma(str) ); // should remove the last comma
function removeLastComma(strng){
var n=strng.lastIndexOf(",");
var a=strng.substring(0,n)
return a;
}
This will remove the last comma and any whitespace after it:
str = str.replace(/,\s*$/, "");
It uses a regular expression:
The / mark the beginning and end of the regular expression
The , matches the comma
The \s means whitespace characters (space, tab, etc) and the * means 0 or more
The $ at the end signifies the end of the string
you can remove last comma from a string by using slice() method, find the below example:
var strVal = $.trim($('.txtValue').val());
var lastChar = strVal.slice(-1);
if (lastChar == ',') {
strVal = strVal.slice(0, -1);
}
Here is an Example
function myFunction() {
var strVal = $.trim($('.txtValue').text());
var lastChar = strVal.slice(-1);
if (lastChar == ',') { // check last character is string
strVal = strVal.slice(0, -1); // trim last character
$("#demo").text(strVal);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="txtValue">Striing with Commma,</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
function removeLastComma(str) {
return str.replace(/,(\s+)?$/, '');
}
In case its useful or a better way:
str = str.replace(/(\s*,?\s*)*$/, "");
It will replace all following combination end of the string:
1. ,<no space>
2. ,<spaces>
3. , , , , ,
4. <spaces>
5. <spaces>,
6. <spaces>,<spaces>
The greatly upvoted answer removes not only the final comma, but also any spaces that follow. But removing those following spaces was not what was part of the original problem. So:
let str = 'abc,def,ghi, ';
let str2 = str.replace(/,(?=\s*$)/, '');
alert("'" + str2 + "'");
'abc,def,ghi '
https://jsfiddle.net/dc8moa3k/
long shot here
var sentence="I got,. commas, here,";
var pattern=/,/g;
var currentIndex;
while (pattern.test(sentence)==true) {
currentIndex=pattern.lastIndex;
}
if(currentIndex==sentence.trim().length)
alert(sentence.substring(0,currentIndex-1));
else
alert(sentence);
Remove last comma. Working example
function truncateText() {
var str= document.getElementById('input').value;
str = str.replace(/,\s*$/, "");
console.log(str);
}
<input id="input" value="address line one,"/>
<button onclick="truncateText()">Truncate</button>
First, one should check if the last character is a comma.
If it exists, remove it.
if (str.indexOf(',', this.length - ','.length) !== -1) {
str = str.substring(0, str.length - 1);
}
NOTE str.indexOf(',', this.length - ','.length) can be simplified to str.indexOf(',', this.length - 1)
you can remove last comma:
var sentence = "I got,. commas, here,";
sentence = sentence.replace(/(.+),$/, '$1');
console.log(sentence);
To remove the last comma from a string, you need
text.replace(/,(?=[^,]*$)/, '')
text.replace(/,(?![^,]*,)/, '')
See the regex demo. Details:
,(?=[^,]*$) - a comma that is immediately followed with any zero or more chars other than a comma till end of string.
,(?![^,]*,) - a comma that is not immediately followed with any zero or more chars other than a comma and then another comma.
See the JavaScript demo:
const text = '1,This is a test, and this is another, ...';
console.log(text.replace(/,(?=[^,]*$)/, ''));
console.log(text.replace(/,(?![^,]*,)/, ''));
Remove whitespace and comma at the end use this,
var str = "Hello TecAdmin, ";
str = str.trim().replace(/,(?![^,]*,)/, '')
// Output
"Hello TecAdmin"
The problem is that you remove the last comma in the string, not the comma if it's the last thing in the string. So you should put an if to check if the last char is ',' and change it if it is.
EDIT: Is it really that confusing?
'This, is a random string'
Your code finds the last comma from the string and stores only 'This, ' because, the last comma is after 'This' not at the end of the string.
With or without Regex.
I suggest two processes and also consider removing space as well. Today I got this problem and I fixed this by writing the below code.
I hope this code will help others.
//With the help of Regex
var str = " I am in Pakistan, I am in India, I am in Japan, ";
var newstr = str.replace(/[, ]+$/, "").trim();
console.log(newstr);
//Without Regex
function removeSpaceAndLastComa(str) {
var newstr = str.trim();
var tabId = newstr.split(",");
strAry = [];
tabId.forEach(function(i, e) {
if (i != "") {
strAry.push(i);
}
})
console.log(strAry.join(","));
}
removeSpaceAndLastComa(str);
If you are targeting es6, then you can simply do this
str = Array.from( str ).splice(0, str.length - 1).join('');
This Array.from(str) converts the string to an array (so we can slice it)
This splice( 0 , str.length - 1 ) returns an array with the items from the array sequentially except the last item in the array
This join('') joins the entries in the array to form a string
Then if you want to make sure that a comma actually ends the string before performing the operation, you can do something like this
str = str.endsWith(',') ? Array.from(str).splice(0,str.length - 1).join('') : str;

split string based on a symbol

I'm trying to split a string into an array based on the second occurrence of the symbol _
var string = "this_is_my_string";
I want to split the string after the second underscore. The string is not always the same but it always has 2 or more underscores in it. I always need it split on the second underscore.
In the example string above I would need it to be split like this.
var split = [this_is, _my_string];
var string = "this_is_my_string";
var firstUnderscore = string.indexOf('_');
var secondUnderscore = string.indexOf('_', firstUnderscore + 1);
var split = [string.substring(0, secondUnderscore),
string.substring(secondUnderscore)];
Paste it into your browser's console to try it out. No need for a jsFiddle.
var string = "this_is_my_string";
var splitChar = string.indexOf('_', string.indexOf('_') + 1);
var result = [string.substring(0, splitChar),
string.substring(splitChar, string.length)];
This should work.
var str = "this_is_my_string";
var matches = str.match(/(.*?_.*?)(_.*)/); // MAGIC HAPPENS HERE
var firstPart = matches[1]; // this_is
var secondPart = matches[2]; // _my_string
This uses regular expressions to find the first two underscores, and captures the part up to it and the part after it. The first subexpression, (.*?_.*?), says "any number of characters, an underscore, and again any number of characters, keeping the number of characters matched as small as possible, and capture it". The second one, (_.*) means "match an underscore, then any number of characters, as much of them as possible, and capture it". The result of the match function is an array starting with the full matched region, followed by the two captured groups.
I know this post is quite old... but couldn't help but notice that no one provided a working solution. Here's one that works:
String str = "this_is_my_string";
String undScore1 = str.split("_")[0];
String undScore2 = str.split("_")[1];
String bothUndScores = undScore1 + "_" + undScore2 + "_";
String allElse = str.split(bothUndScores)[1];
System.out.println(allElse);
This is assuming you know there will always be at least 2 underscores - "allElse" returns everything after the second occurrence.

What's a good RegExp that will strip out all characters except Integers from a string?

I'm new to using regexp, can someone give me the regexp that will strip out everything but an integer from a string in javascript?
I would like to take the string "http://www.foo.com/something/1234/somethingelse" and get it down to 1234 as an integer.
Thanks
var str = "something 123 foo 432";
// Replace all non-digits:
str = str.replace(/\D/g, '');
alert(str); // alerts "123432"
In response to your edited question, extracting a string of digits from a string can be simple, depending on whether you want to target a specific area of the string or if you simply want to extract the first-occurring string of digits. Try this:
var url = "http://www.foo.com/something/1234/somethingelse";
var digitMatch = url.match(/\d+/); // matches one or more digits
alert(digitMatch[0]); // alerts "1234"
// or:
var url = "http://x/y/1234/z/456/v/890";
var digitMatch = url.match(/\d+/g); // matches one or more digits [global search]
digitMatch; // => ['1234', '456', '890']
This is just for integers:
[0-9]+
The + means match 1 or more, and the [0-9] means match any character from the range 0 to 9.
uri = "http://www.foo.com/something/1234/somethingelse";
alert(uri.replace(/.+?\/(\d+)\/.+/, "$1"))
Just define a character-class that requires the values to be numbers.
/[^0-9]/g // matches anything that is NOT 0-9 (only numbers will remain)

Categories