Marco
Marco

Reputation: 501

Replace different words in the same structure with jQuery

I found a solution here to replace single words with jQuery. The solution works for me in general but is it possible to short it a bit? Here's the Code:

$(document).ready(function() {
    $('.who').text(function(i, oldText) {
        return oldText === 'Dritter' ? 'Ich nehm die Nummer drei' : oldText;
    });
    $('.who').text(function(i, oldText) {
        return oldText === 'Fünfter' ? 'Ich nehm die Nummer 5' : oldText;
    });
    $('.groupheader').text(function(i, oldText) {
        return oldText === 'Sechster' ? 'i am number six' : oldText;
    });
});    

For this div structure:

<div class="who">Erster</div>
<div class="who">Zweiter</div>
<div class="who">Dritter</div>
<div class="who">Vierter</div>
<div class="who">Fünfter</div>
<div class="who">Sechster</div>

Upvotes: 1

Views: 55

Answers (2)

John R
John R

Reputation: 2801

You can also shorten your code in this way with ternary operator.

Code snippets:

$(document).ready(function() {
  $('.who,.groupheader').text(function(i, oldText) {
    return oldText === 'Dritter' ? 'Ich nehm die Nummer drei' : oldText === 'Fünfter' ? 'Ich nehm die Nummer 5' : oldText === 'Sechster' ? 'i am number six' : oldText;
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div class="who">Erster</div>
<div class="who">Zweiter</div>
<div class="who">Dritter</div>
<div class="who">Vierter</div>
<div class="who">Fünfter</div>
<div class="who">Sechster</div>

FIDDLE DEMO

Upvotes: 2

Rory McCrossan
Rory McCrossan

Reputation: 337550

You can shorten this by placing all the substitutions within an object, keyed by the text to be changed. You can then have a single line function which replaces the text with the value from the object, should one be found.

var substitutions = {
    'Dritter': 'Ich nehm die Nummer drei',
    'Fünfter': 'Ich nehm die Nummer 5',
    'Sechster': 'i am number six'
}

$('.who, .groupheader').text(function(i, oldText) {
    return substitutions[oldText] || oldText;
});

Working example

Upvotes: 3

Related Questions