2

I have several options values (attribute value) that have spaces,

<option value="Divers RF" class="">Divers RF</option>

<option value="France Bleu" class="">France Bleu</option>

How can I replace the space with a _ in the value?

So the result would be

<option value="Divers_RF" class="">Divers RF</option>
<option value="France_Bleu" class="">France Bleu</option>

and not only for these two options but for all options that have spaces in them.

1
  • could you be more clear... like whether you statically want _ in values or you want to change it with jquery events Commented Jul 25, 2011 at 7:38

3 Answers 3

2

Try this:

$('option').val(function(i,v){
   return v.replace(/\s/g, '_');
});

Working example: http://jsfiddle.net/YQWGw/

Sign up to request clarification or add additional context in comments.

Comments

1
$("option").each(function() {
  var val = $(this).val();
  $(this).val(val.replace(/ /g, '_'));
}

thanks to @Fender, replace should be greedy

EDIT: adopted to replace value instead of text content

2 Comments

you should use $(this).text(val.replace(/ /g, '_')); to replace all occurences
I would look more closely at the question. I believe the OP wants the attributes changed, not the text within the option element.
0
$("option").each(function() {
  $(this).val($(this).val().replace(/ /g, '_'));
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.