Sagive
Sagive

Reputation: 1827

Search and Replace with variable using jquery

i want to search and replace an entire string that has changing text inside it

Example:

<option value="AU">Australia</option>
<option value="AT">Austria</option>
<option value="AZ">Azerbaijan</option>
<option value="BS">Bahamas</option>
<option value="BH">Bahrain</option>
<option value="BD">Bangladesh</option>

To:

Australia
Austria
Azerbaijan
Bahamas
Bahrain
Bangladesh

The problem is of course that changing value... meaning value="$var"... How can search and replace all occurrences using jquery / javascript.

Would appreciate your help.

Upvotes: 0

Views: 1085

Answers (3)

vch
vch

Reputation: 211

This should work:

$('select').children().each(function(i,el){
    $(el).val($(el).text());   
});

Of course, this assumes that's the only select element on the page. If not, you'll either have to choose the right one, hopefully using it's id or, if not maybe using eq().

Upvotes: 0

Andrei CACIO
Andrei CACIO

Reputation: 2119

Have you tried this approach:

$('option').each(function() {
   var text = $(this).text();
   $(this).after(text);
   $(this).remove();
});

I can't test it right now but it should do the job. Let me know how it goes.

OR

You can try this way:

$('option').html(function(index, html)
    return html.replace(/<option[^>]*>([^<]+)<\/option>/g, "$1");
});

Good luck!

Upvotes: 2

T.J. Crowder
T.J. Crowder

Reputation: 1074218

If I'm reading your question right, you're dealing with a string, not with elements, so you can use String#replace:

theString = theString.replace(/<option[^>]*>([^<]+)<\/option>/g, "$1");

replace looks for special sequences in the replacement string, and fills them in from information on the matched occurrence. In this case, I'm using a capture group to capture the bit between <option...> and </option>, then using $1 to replace the overall match with the content of the first capture group.

Complete example: Live Copy *(I've added <br> between them just for output purposes):

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Example</title>
</head>
<body>
<script>
  (function() {
    "use strict";

    var theString =
        '<option value="AU">Australia</option><br>' +
        '<option value="AT">Austria</option>' +
        '<br><option value="AZ">Azerbaijan</option>' +
        '<br><option value="BS">Bahamas</option>' +
        '<br><option value="BH">Bahrain</option>' +
        '<br><option value="BD">Bangladesh</option>';

    theString = theString.replace(/<option[^>]*>([^<]+)<\/option>/g, "$1");
    display(theString);

    function display(msg) {
      var p = document.createElement('p');
      p.innerHTML = String(msg);
      document.body.appendChild(p);
    }
  })();
</script>
</body>
</html>

Upvotes: 2

Related Questions