Rockwell Rice
Rockwell Rice

Reputation: 3002

How to remove second whitespace in string, but not first using js

I have a small text field and if there is more than one whitespace I need to format the string and add a br tag in that second whitespace. If there isn;t then I do not need to do anything. I do not need to target the first or third (if there is one) and there will probably not be any after 3 as this is a short title field. the length of characters will be different and there is not consistent marker, like a comma of period or something, that I can target.

I was unable to find an answer that addressed this. I did find answers using regex but those all had markers like comma to target, I cannot find on that specifically will only target the second occurrence if there is one so any help would be great appreciated.

Code I have now, which targets only the first occurrence.

Array.prototype.forEach.call(awardscount, function() {
  var string = $('#award-' + int).attr('data-award-title');

  var refomrattedTitle = string.replace(" ", "<br>");

  int++;
  console.log(refomrattedTitle);
});

Upvotes: 0

Views: 745

Answers (1)

Ozan
Ozan

Reputation: 3739

var test = "foo bar string test".replace(/([^\s]*\s[^\s]*)\s/, "$1<br/>");
console.log(test); // logs "foo bar<br/>string test"

Upvotes: 3

Related Questions