Tom Molskow
Tom Molskow

Reputation: 23

Split Text Name String in HTML After Page is Rendered

I have a page that is rendering multiple names from a data source. The names render as below:

Jones, TomSmith, JohnBrown, Mary

For the values: Jones, Tom - Smith, John - Brown, Mary

The HTML is as shown below:

<td>Jones, TomSmith, JohnBrown, Mary</td>

I want to break up the output so it looks like this:

Jones, Tom - Smith, John - Brown, Mary

Upvotes: 0

Views: 177

Answers (2)

Shidersz
Shidersz

Reputation: 17190

One solution is to replace every uppercase letter "$" by the "- $" only if the previous letter is lowercase. We can use the replacement function of String.replace() for this:

let test = document.getElementById("test");

test.innerText = test.innerText.replace(/[A-Z]/g, (m, idx, s) =>
{
    return s[idx-1] && /[a-z]/.test(s[idx-1]) ? ` - ${m}` : m;
});
<p id="test">Jones, TomSmith, JohnBrown, Mary</p>

Other possible solution is to replace the pattern <lowercase_letter><uppercase_leter> by <lowercase_letter> - <uppercase_leter>:

let test = document.getElementById("test");
test.innerText = test.innerText.replace(/([a-z])([A-Z])/g, "$1 - $2");
<p id="test">Jones, TomSmith, JohnBrown, Mary</p>

Upvotes: 1

m02ph3u5
m02ph3u5

Reputation: 3161

You can use regular expressions and string replacement for this.

Assuming you have your string in some variable a.

let a = "Jones, TomSmith, JohnBrown, Mary;
let b = a.replace(/([A-Z][a-z]*)([A-Z][a-z]*)/g, "$1 - $2";
console.log(b);

Will output:

"Jones, Tom-Smith, John-Brown, Mary"

How's that? We match an upper case letter followed by any number of lower case letters twice and insert " - " between these matches. The regex ([A-Z][a-z]+)([A-Z][a-z]+) might be more accurate, requiring at least one lower case letter after the upper case ones.


In case you don't know how to get the names from the mark-up or write back to it.

let e = document.querySelector("td"); // you'll have to select the right element here
let a = e.innerText;
let b = a.replace(/([A-Z][a-z]*)([A-Z][a-z]*)/g, "$1 - $2";
e.innerText = b;

Upvotes: 3

Related Questions