prasad prasad - 3 months ago 9
HTML Question

Regex match after delimiter and find higher number of the match?

I have a match equation



function start() {

var str = "10x2+10x+10y100-20y30";
var match = str.match(/([a-z])=?(\d+)/g);//find the higher value of power only and also print the power value only withput alphapets).i need match like "100"

var text;
if(match < 10)
{text = "less 10";}
else if(match == "10")
{text == "equal";}
else
{text ="above 10";}

document.getElementById('demo').innerHTML=text;
}
start();

<p id="demo"></p>





i need match the power values and also getting out with higher power value only.

example :
10x2+10y90+9x91 out --> "90"
.
what wrong with my and corret my regex match with suitable format.Thank You

Answer

The variable match contains all the powers that matches your regex, not just one. You'll have to iterate over them to find the greatest.

I took your code and modified it a bit to work :

function start() {
 
  var str = "10x2+10x+10y100-20y30";
  var match = str.match(/([a-z])=?(\d+)/g);//find the higher value of power only and also print the power value only withput alphapets).i need match like "100"

  var max = 0;
  for (var i = 0; i < match.length; i++) { // Iterate over all matches
    var currentValue = parseInt(match[i].substring(1)); // Get the value of that match, without using the first letter
    if (currentValue > max) {
      max = currentValue; // Update maximum if it is greater than the old one
    } 
  }
  
  document.getElementById('demo').innerHTML=max;
 }
start();
<p id="demo"></p>

Comments