[英]Strip out characters from a string
I have a string similar to BR450L
and I am trying to strip out BR
(from the beginning) and L
from the end.我有一个类似于
BR450L
的字符串,我试图从BR450L
BR
(从头开始)和L
Can anyone assist me with doing that in a single pass.任何人都可以帮助我一次性完成。 I want to use that condition in a
conditional (ternary) operator
and wrap that outcome with a function.我想在
conditional (ternary) operator
使用该条件,并用函数包装该结果。
If the format of the string is constant then...如果字符串的格式是常量,那么...
const stripOutNum = str => Number(str.slice(2, -1))
for example:例如:
stripOutNum('BR450L') // returns 450
If you wanted a function that tests whether the 'inner' number matches another number...如果您想要一个测试“内部”数字是否与另一个数字匹配的函数...
const checkNumMatch = (str, num) => {
return Number(str.slice(2, -1)) === num
}
Extract ALL Digits from a Sting:从 Sting 中提取所有数字:
string.match(/\\d/g)
Returns an Array.返回一个数组。
To cast into String:转换成字符串:
string.match(/\\d/g).join("")
To cast into a Number:转换成数字:
+string.match(/\\d/g).join("")
or parseFloat(string.match(/\\d/g).join(""))
或
parseFloat(string.match(/\\d/g).join(""))
var string = "BR560L"; console.log("string=\\"" + string + "\\""); console.log("as String digit Array=[" + string.match(/\\d/g) + "]"); console.log("as digit String=\\"" + string.match(/\\d/g).join("") + "\\""); console.log("as Number using \\"+\\"=\\"" + (+string.match(/\\d/g).join("")) +"\\""); console.log("as Number using \\"parseFloat\\"=" + parseFloat(string.match(/\\d/g).join("")));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.