[英]How can I extract a number from a string in JavaScript?
I have a string in JavaScript (eg #box2
) and I just want the 2
from it.我在 JavaScript 中有一个字符串(例如
#box2
),我只想要其中的2
。
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?它仍然在警报中返回
#box2
,我怎样才能让它工作?
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"
Since this answer gained popularity for some reason, 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.其中
txt
是您的字符串。
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, '');
尝试以下操作:
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 match function.使用匹配 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
Tried all the combinations cited above with this Code and got it working, was the only one that worked on that string -> (12) 3456-7890
使用此代码尝试了上面引用的所有组合并使其正常工作,是唯一适用于该字符串的组合 ->
(12) 3456-7890
var str="(12) 3456-7890";
str.replace( /\D+/g, '');
Result: "1234567890"
结果:
"1234567890"
Obs: i know that a string like that will not be on the attr but whatever, the solution is better, because its more complete. Obs:我知道这样的字符串不会出现在 attr 上,但无论如何,解决方案更好,因为它更完整。
you may use great parseInt method你可以使用很棒的 parseInt 方法
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 output:25933473
Wrap it into vanilla javascript function:将其包裹成香草 javascript function:
function onlyNumbers(text){
return text.replace(/\D/g, "");
}
For a string such as #box2
, this should work:对于像
#box2
这样的字符串,这应该有效:
var thenum = thestring.replace(/^.*?(\d+).*/,'$1');
jsFiddle: js小提琴:
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
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 wont have it记住:如果数字前面有一个零,则 int 不会有它
If you want to parse a number from a price like $6,694.20.如果您想解析价格为 6,694.20 美元的数字。
It can be done this way:可以这样做:
parseFloat('$6,694.20'.replace( /^\D|,+/g, ''))
or via function:或通过 function:
function parsePrice(value) {
return parseFloat(value.replace( /^\D|,+/g, ''))
}
parsePrice('$6,694.20') // 6694.2
You can use regular expression.您可以使用正则表达式。
var txt="some text 2";
var numb = txt.match(/\d/g);
alert (numb);
That will alert 2.这将提醒 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
To return a int from the string you can do following code.要从字符串中返回一个 int,您可以执行以下代码。 It removes all not number characters and return integer.
它删除所有非数字字符并返回 integer。
Number("strin[g]3".replace(/\D+/g, ""))
You can use Underscore String Library as following您可以使用下划线字符串库如下
var common="#box"
var href="#box1"
_(href).strRight(common)
result will be: 1结果将是:1
See: https://github.com/epeli/underscore.string参见: https://github.com/epeli/underscore.string
DEMO:演示:
http://jsfiddle.net/abdennour/Vyqtt/ http://jsfiddle.net/abdennour/Vyqtt/
HTML Code: HTML 代码:
<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>
JS Code: JS代码:
var comm="#box"
$('a').click(function(){
$('div').html(_($(this).attr('href')).strRight(comm))})
if you have suffix as following:如果你有如下后缀:
href="box1az"
You can use the next demo:您可以使用下一个演示:
http://jsfiddle.net/abdennour/Vyqtt/1/ http://jsfiddle.net/abdennour/Vyqtt/1/
function retrieveNumber(all,prefix,suffix){
var left=_(all).strRight(prefix);
return _(left).strLeft(suffix);
}
With Regular Expressions , how to get numbers from a String, for example:使用Regular Expressions ,如何从字符串中获取数字,例如:
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
" myString
的结果是“ 24
”
you can see an example of this running code here: http://ideone.com/iOCf5G您可以在此处查看此运行代码的示例: http://ideone.com/iOCf5G
Here's a solt.这是一个 solt。 that checks for no data
检查没有数据
var someStr = 'abc'; // add 123 to string to see inverse
var thenum = someStr.match(/\d+/);
if (thenum != null )
{
console.log(thenum[0]);
}
else
{
console.log('no 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
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 below javaScripts, there you can get only number请检查下面的javaScripts,那里你只能得到数字
var txt = "abc1234char5678#;9". var str = txt,match(/\d+/g; "")+''. var s = str,split('.');join(''); alert(Number(s));
output: 1234567789
output:
1234567789
This answer will cover most of the scenario.这个答案将涵盖大部分场景。 I can across this situation when user try 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 a array of string as output >> ["34", "56766"]
它将给出一个字符串数组 output >> ["34", "56766"]
str.match(/\d+/g).join("")
join will convert and concatenate that array data into single string join 会将数组数据转换并连接成单个字符串
output >> "3456766"
output >> "3456766"
In my example I need the output as 209-356-6788 so I used replace
在我的示例中,我需要 output 作为 209-356-6788,所以我使用了替换
$('#help_number').keyup(function(){
$(this).val($(this).val().match(/\d+/g).join("").replace(/(\d{3})\-?(\d{3})\-?(\d{4})/,'$1-$2-$3'))
});
You need to add "(/\d+/g)" which will remove all non-number text, but it will still be a string at this point.您需要添加“(/\d+/g)”,这将删除所有非数字文本,但此时它仍然是一个字符串。 If you create a variable and "parseInt" through the match, you can set the new variables to the array values.
如果通过匹配创建变量和“parseInt”,则可以将新变量设置为数组值。 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]);
written without regex没有正则表达式编写
// 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
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 function where you need, with parameter.您可以这样做,然后在需要的地方使用参数调用 function。
this.changeStrangeDate('/Date(1551401820000-0100)/');
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)
) )
Одного разу тамада на весіллі вирішив розважити гостей, і встановив правило: як тільки приходить новий гість, кожен п'є по одній порції випивки! Одногоразутамаданавесіллівирішиврозважитигостей,івстановивправило:яктількиприходитьновийгість,коженп'єпооднійпорціївипивки!
Давай допоможемо тамаді порахувати, скільки порцій випивки потрібно приготувати, і напишемо функцію getDrinks. Давай допоможемо тамаді порахувати, скільки порцій випивки потрібно приготувати, і нкапиушемо Вона приймає ціле число numberOfGuests і повертає необхідну кількість порцій випивки, щоб вистачило усім гостям.
Вона приймає ціле число numberOfGuests і повертає необхідну кількість порцій випивки, щоб вистачилоусть
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.