-5

I have a string like this

var assignments= "NAME1,NAME2,NAME3,NAME4,NAME5,NAME6"

how do i print only first three strings like this "NAME1,NAME2,NAME3" in JavaScript

user2314737
  • 27,088
  • 20
  • 102
  • 114
Suresh R
  • 71
  • 1
  • 10

2 Answers2

0

You can do this way

let string= "NAME1,NAME2,NAME3,NAME4,NAME5,NAME6".split(',')
let output = string.splice(',',3).join(',')
console.log(output)
Narendra Chouhan
  • 2,291
  • 1
  • 15
  • 24
0

Using standard Array functions you can do what you want. The code below shows the various stages, though you can write it more concisely as one line if you like.

var assignments= "NAME1,NAME2,NAME3,NAME4,NAME5,NAME6"
var splitAssignements = assignments.split(",")
var firstThreeArray = splitAssignements.slice(0,3)
var firstThreeString = firstThreeArray.join(",")
console.log(firstThreeString)
Always Learning
  • 5,510
  • 2
  • 17
  • 34