Obtain a specific text fraction with jquery

3

I have this variable

var data = "<option codigo='1'></option>,<option codigo='2'></option>";

and I want to get only what is inside codigo='' that is, get 1,2

    
asked by Andre Mateo Chavez 13.02.2018 в 06:26
source

1 answer

2

If someone tells you that you have to analyze it with functions on the string, it would be a serious mistake. The correct way to do it is to take the sctring to DOM. In jQuery, we use $. ParseHTML () :

var data = "<option codigo='1'></option>,<option codigo='2'></option>";

var html = $.parseHTML(data);

var resultado = $(html).map(function() {
  return $(this).attr('codigo');
})
.get()
.join(',');

console.log('Resultado:', resultado);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

$.parseHTML() returns an array of nodes, about which we use .map() to filter the information we want: in this case .attr('codigo') .

    
answered by 13.02.2018 / 07:16
source