Skip to content Skip to sidebar Skip to footer

How To Get A Term Before A Character?

How to get the number before 'x'? I tried using .split('x')[0] but it grabs everything before 'x'. 123x // Gives 123 123y+123x - // Gives 123 123x+123x - // Gives 246

Solution 1:

I've tested a function which uses regex that I think will work. I've included the results, an explanation of how the function works, and then a commented version of the function.

Note, this doesn't handle any algebra more complex than adding and subtracting simple terms. I would refer to https://newton.now.sh/ for that, it's an API which can handle simplification (I am not affiliated).

Results:

console.log(coefficient("-x+23x"));     // 22
console.log(coefficient("123y+123x"));  // 123
// replaces spaces
console.log(coefficient("x + 123x"));   // 124
console.log(coefficient("-x - 123x"));  // -124
console.log(coefficient("1234x-23x"));  // 1211
// doesn't account for other letters
console.log(coefficient("-23yx"));      // 1

Explanation:

First the function removes spaces. Then it uses a regex, which finds any sequence of numbers that are followed by an 'x'. If there's a +/- in front, the regex keeps that. The function loops through these sequences of numbers, and adds them to a total. If there's an 'x' that does not have numbers with it, its coefficient is assumed as -1 or 1.

Commented Code:

function coefficient(str) {
  // remove spaces
  str = str.replace(/\s/g, '');

  // all powerful regex
  var regexp = /(\+|-)?[0-9]*x/g

  // total
  sum = 0;

  // find the occurrences of x
  var found = true;
  while (found) {
    match = regexp.exec(str);
    if (match == null) {
      found = false;
    } else {
      // treated as +/- 1 if no proceeding number
      if (isNaN(parseInt(match[0]))) {
        if (match[0].charAt(0) == "-") {
          sum--;
        } else {
          sum++;
        }
      // parse the proceeding number
      } else {
        sum += parseInt(match[0]);
      }
    }
  }
  return sum;
}

Solution 2:

I don't know if there is sufficient cleverness in ECMAScript regular expressions to do look behind, but you can do it with match and post processing to remove the "x".

If the intention is to sum the terms, then a further operation with reduce is required. Trimming the x could be combined with reduce so that map isn't required.

console.log(
  '123x+123x'.match(/\d+x/ig).map(function(v){
    return v.slice(0,-1)
  }).reduce(function(sum, v){return sum + +v},0)
);

Solution 3:

console.log(match('123x+123y+456x', 'x'))
console.log(match('123x+123y+456x', 'y'))

function match(str, x) {
  return str.match(new RegExp('\\d+' + x, 'g')).reduce((cur, p) => {
    return cur + parseInt(p.substr(0, p.length - x.length))
  }, 0)
}

Post a Comment for "How To Get A Term Before A Character?"