0

I may have a link formated with the following text in these 3 flavors, on my custom page...

<h3 class="ms-srch-ellipsis"><a class="ms-srch-item-link" href="...">this_old_house_is_broken</a></h3>
<h3 class="ms-srch-ellipsis"><a class="ms-srch-item-link" href="...">this-old-house-is-broken</a></h3>
<h3 class="ms-srch-ellipsis"><a class="ms-srch-item-link" href="...">ThisOldHouseIsBroken</a></h3>

What is a best practice approach with jQuery, to check all ms-srch-ellipsis elements and fix the text to look like this...

<h3 class="ms-srch-ellipsis"><a href="...">This Old House Is Broken</a></h3>

I started with this approach, just to get somewhere...but it doesn't change anything...

$( ".ms-srch-item-link" ).each(function(e) {
  $(this).text().replace('-',/\s+/g);       
    $(this).text().replace('_',/\s+/g);     
});
klewis
  • 7,459
  • 15
  • 58
  • 102
  • `text()` accepts the argument that must be set. `.text('foo')` will set it to `foo`. – zerkms Mar 12 '15 at 21:35
  • ....you mean I have to put the condition inside the brackets as upose to the right of it? – klewis Mar 12 '15 at 21:36
  • Condition? What condition? – zerkms Mar 12 '15 at 21:36
  • To change the text you must pass a value as a `.text()` function argument, like `.text(new_value)`. When you simply call `.text()` without arguments it just returns the current value, nothing more – zerkms Mar 12 '15 at 21:38
  • You'll have to capture the result of `.replace()`. It doesn't modify the text itself. `$(this).text($(this).text().replace('-',/\s+/g));` – Jonathan Lonowski Mar 12 '15 at 21:39
  • it works, I'm just not using the right replace code for empty space... – klewis Mar 12 '15 at 21:43
  • You can also pass a function to text() that takes the text content and returns the modified version: http://api.jquery.com/text/#text-function – radiaph Mar 12 '15 at 21:43
  • This answer may help you write the replace expression: http://stackoverflow.com/questions/7662936/using-replace-and-regex-to-capitalize-first-letter-of-each-word-of-a-string-in-j – radiaph Mar 12 '15 at 21:45

1 Answers1

0
$( ".ms-srch-item-link" ).each(function(e) {
  $(this).text().replace(function(i, text) { // apply replacement function
    return text.charAt(0).toUpperCase +      // capitalize first letter
           text.substring(1).
             replace(/([a-z])([A-Z])/g, function(m, g1, g2) { // camel case
               return g1 + " " + g2;
             }).
             replace(/(_|-)([a-z])/g, function(m, g1, g2) { // dash/underscore
               return " " + g2.toUpperCase();
             });

  });
});
radiaph
  • 4,001
  • 1
  • 16
  • 19