JF-Mechs
JF-Mechs

Reputation: 1081

array splice doesn't work with array formatted string (split string)?

Why does array splice doesn't work with array formatted string? When I say array formatted string I mean I use split() to make string into array.

function _formatText(text) {
  var textList = text.replace(/\s+/g, ",").split(",");
  return textList.splice(1, 0, "<br />").join(" ");
}

alert(_formatText("VERY VERY LONG TEXT"))

Upvotes: 1

Views: 217

Answers (2)

Redu
Redu

Reputation: 26161

You don't need the string replace method. With some reduced code you can also do like this.

function _formatText(text) {
  var textList = text.split(/\s+/);
  return textList.slice(0,1).concat("</br>",textList.slice(1)).join(" ");
}

alert(_formatText("VERY VERY LONG TEXT"))

Upvotes: 0

Pranav C Balan
Pranav C Balan

Reputation: 115232

The Array#splice() method returns the array of removed elements, in your case it's empty array and you are applying join on the returned array.

So you need to rearrange it like this.

function _formatText(text) {
  var textList = text.replace(/\s+/g, ",").split(",");
  textList.splice(1, 0, "<br />");
  return textList.join(" ");
}

alert(_formatText("VERY VERY LONG TEXT"))

Upvotes: 1

Related Questions