jQuery, if contains X, do this, but conditional? -
i have line being populated database requires different formatting based on has been entered. there 3 types of formats:
line example 1) $3.00
line example 1) 2 per person $4.95
line example 2) small $5.00 | medium $10.00 | large $15.00
line 1) no changes required
line 2) need insert space before $
line 3) need insert space before , after | not before $ (all instances)
i've looked around , tried piece things can't quite it. here's have far:
$('.menu-price-value:contains("$")').each(function() { var newtext = $(this).html().replace('$', '<span class="space"></span>$'); $(this).html(newtext); }); $('.menu-price-value:contains("|")').each(function() { var newtext = $(this).html().replace("|", " | "); $(this).html(newtext); $('.menu-price-value').addclass('remove-space'); });
there few problems
- javascript string
replace
replaces first match (bit lame know). use regexg
(global) option replace occurances. - you targetting matching classes in second example (not current match)
jsfiddle: http://jsfiddle.net/trueblueaussie/evn91m7y/1/
$('.menu-price-value:contains(" $")').html(function () { return $(this).html().replace(/\$/g, '<span class="space"> </span>$'); }); $('.menu-price-value:contains("|")').html(function () { return $(this).html().replace(/\|/g, " | "); }).addclass('remove-space');
to avoid running $
check on |
matches, can add :not(contains("|"))
this:
$('.menu-price-value:contains(" $"):not(:contains("|"))').html(function () { return $(this).html().replace(/\$/g, '<span class="space"> </span>$'); });
e.g. http://jsfiddle.net/trueblueaussie/evn91m7y/2/
or reverse check order , chain selectors .not()
this: http://jsfiddle.net/trueblueaussie/evn91m7y/4/
notes:
- you can use function
html()
, replaced html returned value of each element. - i differentiated between first example , others using fact other examples have space before
$
. alternative see of value starts with$
or not. - i had add styling make
space
span visible. - i exaggerated changes styling see them more easily.
Comments
Post a Comment