1

I am trying to extract some strings from a word with some pattern like -

"38384-1-page1-2222", "1-22-page33-02", "99-222-frontpage-111"

how will I extract all word between - separately, means first word before - and then second word between - and - and so on...

string = "38384-1-page1-2222";
string.substr(0, string.indexof("-")); //return 38384

But how will I extract 1, page1 and 2222 all the words separately?

kate moss
  • 416
  • 1
  • 5
  • 18
  • `string.split("-");` ? – Anurag Srivastava Sep 03 '22 at 08:37
  • Why not using the str split function? Something like `const splitedText= text.split("-");` [Check this out.](https://www.w3schools.com/jsref/jsref_split.asp) – herostoky Sep 03 '22 at 08:38
  • I understood but how will I get ll the values i.e. 4 values separately so that I will assign that values separately ? – kate moss Sep 03 '22 at 08:39
  • @herostoky this `string.split("-")` gives me values at once so I will not able to use them separately – kate moss Sep 03 '22 at 08:41
  • 1
    Does this answer your question? [How do I split a string, breaking at a particular character?](https://stackoverflow.com/questions/96428/how-do-i-split-a-string-breaking-at-a-particular-character) – Anurag Srivastava Sep 03 '22 at 08:42

3 Answers3

2

The javascript function str.split(separator) split the string by the given separator and it returns an array of all the splited string. REF Here

Here is an example following your question :

var string = "38384-1-page1-2222";
var separator = "-";

var separated = string.split(separator);

var firstString = separated[0];  // will be '38384'
var secondString = separated[1]; // will be '1'
var thirdString = separated[2];  // will be 'page1'
/* And So on ... */
herostoky
  • 107
  • 1
  • 8
2

Hope this can help

Use String.prototype.split() to get your string into array

var words = ["38384-1-page1-2222", "1-22-page33-02", "99-222-frontpage-111"];

var resultArray = [];

for (let i = 0; i < words.length;i++) {
  let temp = words[i];
  resultArray = pushArray(temp.split("-"), resultArray)
}

console.log(resultArray)

function pushArray (inputArray, output) {
  for (let i = 0; i < inputArray.length;i++) {
   output.push(inputArray[i]);
  }
  return output;
}

Or simply use Array.prototype.reduce()

var words = ["38384-1-page1-2222", "1-22-page33-02", "99-222-frontpage-111"];

var result = words.reduce((previousValue, currentValue) => previousValue.concat(currentValue.split("-")), []) 

console.log(result)
HsuTingHuan
  • 615
  • 1
  • 7
  • 23
2

You can use regex /[^-]+/g

const words = ["38384-1-page1-2222", "1-22-page33-02", "99-222-frontpage-111"];

console.log(words.map(v=>v.match(/[^-]+/g)).flat())
Chau Giang
  • 1,414
  • 11
  • 19