我正在处理一个充满名称的HTML列表,每个名称都以这种格式编写:
“的姓名-姓氏/ ” (例如:john-smith /)
所以我很想知道我是否可以使用JavaScript将文本格式更改为:
“名字姓氏” (例如:John Smith)
由于我对JavaScript比较陌生,而且我还没有做过很多关于语言的工作,而且我无法做到这一点。
以下是HTML列表的片段:
<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>
另外,如果我不够清楚,我不想更改href,只需要更改显示的实际文本。
答案 0 :(得分:5)
您可以使用Regex执行此操作:
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]));
}
});
&#13;
<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>
&#13;
答案 1 :(得分:3)
或者你也可以这样做
// target the anchor tags inside the list items
var namesList = document.querySelectorAll('#namesList li a');
// loop through
for (var i = 0; i < namesList.length; ++i) {
// text value, use trim to get rid of spaces on right and left sides of the string
var text = namesList[i].textContent.trim(),
// number of chars in text - 1, thus we automatically eliminate the last
// char "/" in each string
textL = text.length - 1,
firstName, lastName, theIndex;
// we determine the number where the symbol - lies
theIndex = text.indexOf('-');
// for firstName, turn the first char to upper case, and append
// characters from the second char to the index of "-" minus 1
firstName = text.charAt(0).toUpperCase() + text.substring(1, theIndex);
// for lastName, turn the first char AFTER the index of "-" to upper case, and append
// characters from index + 1 to the value of text length
lastName = text.charAt(theIndex + 1).toUpperCase() + text.substring(theIndex + 2, textL);
console.log(firstName + ' ' + lastName);
// join firstName and lastName with space in between
namesList[i].textContent = firstName + ' ' + lastName;
}
<ul id="namesList">
<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>