1

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"))

2 Answers 2

1

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"))

Sign up to request clarification or add additional context in comments.

Comments

0

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"))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.