goldlife
goldlife

Reputation: 1989

Get all characters except hyphen and brackets from string using javascript regex

I have a string like this:

var myString = "MyString-[ADDAAD]-isGreat";

I want to extract this string into 3 parts:

var stringOne = "MyString-";
var stringTwo = "ADDAAD";
var stringThree = "-isGreat";

I know how to get the string between the two square brackets:

var matches = patternString.match(/\[(.*?)\]/);

now matches[1] contains ADDAAD But how can I get the other two parts?

Upvotes: 3

Views: 1028

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626758

You may split the string with your regex. Note that all the capturing group contents will be also part of the resulting array. To avoid empty items, you may add .filter(Boolean) after split().

See a JS demo below:

var myString = "MyString-[ADDAAD]-isGreat";
console.log(myString.split(/\[(.*?)]/).filter(Boolean));
console.log("s1-[s2]".split(/\[(.*?)]/).filter(Boolean));

Note you do not have to escape a ] used outside character classes, it is always parsed as a literal closing bracket if there is no corresponding [ before it.

Upvotes: 2

Mohammad
Mohammad

Reputation: 21489

Select every character except -, [ and ] using bottom regex.

var myString = "MyString-[ADDAAD]-isGreat";
var parts = myString.match(/[^-\[\]]+/g);
console.log(parts);

So if you want to store values in custom variable, use bottom code

var stringOne = parts[0];
var stringTwo = parts[1];
var stringThree = parts[2];

Upvotes: 3

Related Questions