Reputation: 72
How to find last space of the para using JavaScript and replace it with
?
<p class="no-space">Web Development Reading List</p>
(The space between the words "Reading" and "List" to be removed and want to have $nbsp; in place of that.
ie, Reading List
Upvotes: 1
Views: 4919
Reputation: 4100
Use a replace with Regexp:
Using ID
var noSpace = document.getElementById("noSpace");
noSpace.innerHTML = noSpace.innerHTML.replace(/ (?=[^ ]*$)/i, "&nbsp;");
<p class="no-space" id="noSpace">Web Development Reading List</p>
Using class name:
var noSpace = document.getElementsByClassName("no-space");
for (var i = 0; i < noSpace.length; i++) {
noSpace[i].innerHTML = noSpace[i].innerHTML.replace(/ (?=[^ ]*$)/i, "&nbsp;");
}
<p class="no-space">Web Development Reading List</p>
<p class="no-space">Web Development Reading List</p>
<p class="no-space">Web Development Reading List</p>
You can change &nbsp;
to " "
if you need the character instead of the string.
Upvotes: 2
Reputation: 23858
Find your character by lastIndexOf()
and use subStr
to replace it through concatenation.
str = "Any string you want";
var lastIndex = str.lastIndexOf(" ");
str = str.substr(0, lastIndex) + ' ' + str.substr(lastIndex + 1);
Upvotes: 9