Dan Dan - 4 months ago 12
HTML Question

Modifying HTML text & replacing it

I am working on an HTML list full of names, and each name is written in this format:

"firstname-lastname/"
(example: john-smith/)

So I was curious to know if I could use JavaScript to change the format of the text into:

"Firstname Lastname"
(example: John Smith)

As I am relatively new to JavaScript, and I haven't done much work with it the language yet, and I wasn't able to do this.

Here is a snippet of the HTML list:

<ul>
<li><a href="john-smith/"> john-smith/</a></li>
<li><a href="joe-smith/"> joe-smith/</a></li>
<li><a href="gina-smith/"> gina-smith/</a></li>
<li><a href="tom-smith/"> tom-smith/</a></li>
<li><a href="peter-smith/"> peter-smith/</a></li>
</ul>


Also, if I wasn't clear enough, I do not want to change the href, just the actual text that is displayed.

Answer

You can do this with Rejex:

var REGEX_FIND = /(.*?)-(.*?)\/$/;

//From: http://stackoverflow.com/questions/1026069/capitalize-the-first-letter-of-string-in-javascript
function capitalizeFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
}

$('ul li a').each(function() {
  var text = $(this).text().trim();
  
  var m;
  
  if ((m = REGEX_FIND.exec(text)) !== null) {
    $(this).text(capitalizeFirstLetter(m[1]) + ' ' + capitalizeFirstLetter(m[2]));
  }
});

 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li><a href="john-smith/"> john-smith/</a></li>
<li><a href="joe-smith/"> joe-smith/</a></li>
<li><a href="gina-smith/"> gina-smith/</a></li>
<li><a href="tom-smith/"> tom-smith/</a></li>
<li><a href="peter-smith/"> peter-smith/</a></li>
</ul>