-4

I have a string like below

  Ontario;Northwest Territories;Nunavut;Prince Edward Island

from this string I need to create an array of string like

 territoty:Array<string> = [Ontario,Northwest Territories,Nunavut,Prince 
 Edward Island]

in javascript.

How can I create the array from the string?

pash
  • 15
  • 2
  • 7
  • 4
    `territory = str.split(';')`, and you probably mean typescript. – Federico klez Culloca May 20 '19 at 12:54
  • 6
    Please do a reasonable amount of research before posting a question. A Google search using the title of your question turns up the split method in the very first hit. Don't use Stack Overflow as a search engine. – John Coleman May 20 '19 at 12:56

3 Answers3

0

Use split:

var arrayString = 'Ontario;Northwest Territories;Nunavut;Prince Edward Island';
var territories = arrayString.split(';');
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
FleMo
  • 539
  • 6
  • 20
-1
let territories = 'Ontario;Northwest Territories;Nunavut;Prince Edward Island'.split(';');

The split method is available on strings. It takes a string1 as an argument and this argument is the delimiter upon which the original string is split. The method then returns an array of strings.

So for your string, ; is the delimiter. It delimits the territory names. The array of territory names is what is returned.


  1. you can also pass in a regular expression, but that is not relevant for this problem.
Matt Ellen
  • 11,268
  • 4
  • 68
  • 90
-1
var str = 'Ontario; Northwest Territories; Nunavut; Prince Edward Island'
    var array = str.split(";"); 
    document.write(array); 
Mohit Yadav
  • 54
  • 2
  • 7