2

I have a textarea filled with some content.

Something like this:

Some line of text [185047078]1x some more text of - Type 1
[185047138]1x some other text of - Type 2

What I'm trying to do is to strip all text except [185047078] and [185047138]. I want to create an array later on with that data. Since the data between the brackets is dynamically and also the textarea can have 20 more lines of text I'm looking to create a logical way of stripping this textarea.

But I'm not sure what would be the way to start to strip this textarea. Since you can't search or something to search in the textarea the only option is too strip all text?

But I have no idea on how to start.

What I tried is:

var txt = $(this).text() 


txt = txt.match(/\d/g).join('')
txt = txt.replace(/\D/g,'');
txt = txt.replace(/&\/\\#,+()$~%.'":*?<>{}/g, '');

What is the correct syntax to strip this textarea so I'll end up with [185047078] and [185047138]?

Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
Meules
  • 1,349
  • 4
  • 24
  • 71

4 Answers4

1

You could match all non bracket parts followed by a closing bracket.

var string = 'Some line of text [185047078]1x some more text of - Type 1\n[185047138]1x some other text of - Type 2',
    values = string.match(/[^\]\[]+(?=\])/g);

console.log(values);

An array with values in brackets

var string = 'Some line of text [185047078]1x some more text of - Type 1\n[185047138]1x some other text of - Type 2',
    values = string.match(/\[[^\]]+\]/g);

console.log(values);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0
(?<=\[)(.*?)(?=\])

you can add the brackets again if you really need them.

see: https://regex101.com/r/tRXY7r/1

Bart
  • 515
  • 5
  • 12
0

try

txt.match(/\[\d*\]/g)

where

  • \[ and \] means that matched string shoud start by [ and end by ]
  • \d* means digit sequence (between square brackets)
  • g means find all (not first)

let txt = data.value.match(/\[\d*\]/g);
console.log(txt);
<textarea id="data">Some line of text [185047078]1x some more text of - Type 1
[185047138]1x some other text of - Type 2</textarea>
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
0

Just define the regex, in this case /(\[)(.*?)(\])/ and then use that to select the text from the string

    let regex = /(\[)(.*?)(\])/;
    //the text to search 
    let text = "Some line of text [185047078]1x some more text of"
    //regex result
    let result = regex.exec(text);
    
    console.log(result);

This will give you an array with 4 elements. The entire value, a string containing the first part of the regex, a string containing the middle part and a string containing the last bit of the regex.

E S
  • 358
  • 4
  • 15