[英]In Javascript, how to find a character in a string and put all the characters before it in a variable
In javascript, I am trying to make a program that had to do with fractions that you can input and I need a function that will convert a fraction in this format( "10/27") to either 10 or 27 depending on user specification but I don't know how I would code this function. 在javascript中,我正在尝试制作一个与您可以输入的分数有关的程序,并且我需要一个函数,该函数将根据用户规范将此格式(“ 10/27”)的分数转换为10或27,但是我不知道如何编写此函数。 Any code or suggestions to get me started would be much appreciated.
任何使我入门的代码或建议将不胜感激。
Considering str
contains the input value then, 考虑到
str
包含输入值,
a = str.substring(str.indexOf("/")+1);
b = str.substring(0, str.indexOf("/"));
Output: if str is "10/17"
then, 输出:如果str为
"10/17"
,
a == 17;
b == 10;
You can split the string into an array with split()
, then take the first or second part as the numerator or denominator: 您可以使用
split()
将字符串拆分为一个数组,然后将第一部分或第二部分作为分子或分母:
function getNumerator(fraction) {
// fraction = "10/27"
return fraction.split("/")[0];
}
function getDenominator(fraction) {
// fraction = "10/27"
return fraction.split("/")[1];
}
var fraction = "10/27".split("/");
var numerator = fraction[0];
var denominator = fraction[1];
You can of course use a library for it too: https://github.com/ekg/fraction.js 您当然也可以为其使用一个库: https : //github.com/ekg/fraction.js
With this library the answer would be: 使用此库,答案将是:
(new Fraction(10, 27)).numerator
You can search in string using indexOf()
. 您可以使用
indexOf()
在字符串中搜索。 It returns first position of searched string. 它返回搜索到的字符串的第一个位置。
If you want to split string using a character in it, use split()
. 如果要在其中使用字符分割字符串,请使用
split()
。 It will return an array. 它将返回一个数组。 So for eg: in you string 27/10 , indexOf / is 3 but if you do split, you will get array of 2 values, 27 and 10.
因此,例如:在您的字符串27/10中 ,indexOf /为3,但是如果您进行分割,则将得到2个值的数组27和10。
function splitString(str, searchStr) { return str.split(searchStr); } function calculateValue(str) { var searchStr = '/'; var values = splitString(str, searchStr); var result = parseInt(values[0]) / parseInt(values[1]); notify(str, result); } function notify(str, result) { console.log(result); document.getElementById("lblExpression").innerText = str; document.getElementById("lblResult").innerText = result; } (function() { var str = "27/10"; calculateValue(str) })()
Expression: <p id="lblExpression"></p> Result: <p id="lblResult"></p>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.