Binu
Binu

Reputation: 72

How to find last space of a string using JavaScript and replace it with ` `?

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&nbsp;List

Upvotes: 1

Views: 4919

Answers (2)

Magicprog.fr
Magicprog.fr

Reputation: 4100

Use a replace with Regexp:

Using ID

var noSpace = document.getElementById("noSpace");
noSpace.innerHTML = noSpace.innerHTML.replace(/ (?=[^ ]*$)/i, "&amp;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, "&amp;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 &amp;nbsp; to "&nbsp;" if you need the character instead of the string.

Upvotes: 2

Charlie
Charlie

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) + '&nbsp' + str.substr(lastIndex + 1);

Upvotes: 9

Related Questions