Javascript - return string between square brackets
Use grouping. I've added a ?
to make the matching "ungreedy", as this is probably what you want.
var matches = mystring.match(/\[(.*?)\]/);
if (matches) {
var submatch = matches[1];
}
Regex to grab strings between square brackets
You are almost there, you just need a global match (note the /g
flag):
match(/\[(.*?)\]/g);
Example: http://jsfiddle.net/kobi/Rbdj4/
If you want something that only captures the group (from MDN):
var s = "pass[1][2011-08-21][total_passes]";
var matches = [];
var pattern = /\[(.*?)\]/g;
var match;
while ((match = pattern.exec(s)) != null)
{
matches.push(match[1]);
}
Example: http://jsfiddle.net/kobi/6a7XN/
Another option (which I usually prefer), is abusing the replace callback:
var matches = [];
s.replace(/\[(.*?)\]/g, function(g0,g1){matches.push(g1);})
Example: http://jsfiddle.net/kobi/6CEzP/
Regex - Extract string between square bracket tag
We can try matching using the following regex pattern:
\[note\]([\s\S]*?)\[\/note\]
This says to just capture whatever comes in between [note]
and the closest closing [/note]
tag. Note that we use [\s\S]*
to potentially match desired content across newlines, should that be necessary.
var re = /\[note\]([\s\S]*?)\[\/note\]/g;var s = 'Want to extract data [note]This is the text I want to extract[/note]\nbut this is not only tag [note]Another text I want to [text:sample]\n extract[/note]. Can you do it?';var m;
do { m = re.exec(s); if (m) { console.log(m[1]); }} while (m);
JavaScript: How to get string between brackets
Both of these examples assume that the string will always have a set of parenthesis, opening before closing.
I suggest using substring and indexOf for this:
var result = myString.substring( myString.indexOf( '(' ) + 1, myString.indexOf( ')' ) );
You can also use a regex if you prefer:
var result = /\(([^)]*)\)/.exec(myString)[1];
Find contents between square brackets and quotations
There is no support for recursion in JavaScript's regex syntax, so you'll need to throw in some code in order to cope with an arbitrary depth of bracket nesting.
I would therefore go for splitting the string into:
- quotations (starting and ending with an quotation mark, taking into account backslash escaping)
- A substring that does not have any of
'"[]
characters - A single
[
or]
Then use a depth counter to keep track how deeply the brackets are so you know when to build a bracket substring by concatenating the tokens along the way.
Here is a snippet, using a bit more complex input string than you provided:
function solve(str) {
let tokens = str.match(/(['"])((\\.|.)*?)\1|[^[\]'"]+|./g);
let brackets = [];
let quotations = [];
let bracket = "";
let depth = 0;
for (let token of tokens) {
if (token[0] === '"' || token[0] === "'") {
quotations.push(token.slice(1, -1));
} else if (token === "[") {
depth++;
} else if (token === "]") {
depth--;
if (depth < 0) throw "Unbalanced brackets";
if (!depth) {
brackets.push(bracket.slice(1));
bracket = "";
}
}
if (depth) bracket += token;
}
if (depth) throw "Unbalanced brackets";
return {quotations, brackets};
}
const string = String.raw`command [stuff] [stuff [inside [very inside with "escaped \" bracket:]" ]] this] "string" "another [thing] string"`;
console.log(solve(string));
Get text between two rounded brackets
console.log( "This is (my) simple text".match(/\(([^)]+)\)/)[1]);
How to extract text in square brackets from string in JavaScript?
Research:
After having searched in Stack Overflow, I have only found two solutions, both of which using Regular Expressions
and they can be found here:
→ (?<=\[)(.*?)(?=\])
(1)
(?<=\[)
: Positive Lookbehind.\[
:matches the character[
literally.(.*?)
: matches any character except newline and expands as needed.(?=\])
: Positive Lookahead.\]
: matches the character]
literally.
→ \[(.*?)\]
(2)
\[
: matches the character[
literally.(.*?)
: matches any character except newline and expands as needed.\]
: matches the character]
literally.
Notes:
(1) This pattern throws an error in JavaScript
, because the lookbehind operator is not supported.
Example:
console.log(/(?<=\[)(.*?)(?=\])/.exec("[a][b][c][d][e]"));
Uncaught SyntaxError: Invalid regular expression: /(?<=\[)(.*?)(?=\])/: Invalid group(…)
(2) This pattern returns the text inside only the first pair of square brackets as the second element.
Example:
console.log(/\[(.*?)\]/.exec("[a][b][c][d][e]"));
Returns: ["[a]", "a"]
Solution:
The most precise solution for JavaScript
that I have come up with is:
var string, array;
string = "[a][b][c][d][e]";
array = string.split("["); // → ["", "a]", "b]", "c]", "d]", "e]"]
string = array1.join(""); // → "a]b]c]d]e]"
array = string.split("]"); // → ["a", "b", "c", "d", "e", ""]
Now, depending upon whether we want the end result to be an array or a string we can do:
array = array.slice(0, array.length - 1) // → ["a", "b", "c", "d", "e"]
/* OR */
string = array.join("") // → "abcde"
One liner:
Finally, here's a handy one liner for each scenario for people like me who prefer to achieve the most with least code or our TL;DR
guys.
Array:
var a = "[a][b][c][d][e]".split("[").join("").split("]").slice(0,-1);
/* OR */
var a = "[a][b][c][d][e]".slice(1,-1).split(']['); // Thanks @xorspark
String:
var a = "[a][b][c][d][e]".split("[").join("").split("]").join("");
Regular Expression to get a string between parentheses in Javascript
You need to create a set of escaped (with \
) parentheses (that match the parentheses) and a group of regular parentheses that create your capturing group:
var regExp = /\(([^)]+)\)/;var matches = regExp.exec("I expect five hundred dollars ($500).");
//matches[1] contains the value between the parenthesesconsole.log(matches[1]);
Regular expression to extract text between square brackets
You can use the following regex globally:
\[(.*?)\]
Explanation:
\[
:[
is a meta char and needs to be escaped if you want to match it literally.(.*?)
: match everything in a non-greedy way and capture it.\]
:]
is a meta char and needs to be escaped if you want to match it literally.
Related Topics
Random Alpha-Numeric String in JavaScript
Is Reading the 'Length' Property of an Array Really That Expensive an Operation in JavaScript
How to Get Class Object's Name as a String in JavaScript
How to Remove Spaces from a String Using JavaScript
Date.Setmonth' Causes the Month to Be Set Too High If 'Date' Is at the End of the Month
Split String Only on First Instance of Specified Character
JavaScript Es6 Class Definition Not Accessible in Window Global
Classical Inheritance VS Prototypal Inheritance in JavaScript
Chrome Extension: Port Error: Could Not Establish Connection. Receiving End Does Not Exist
Why Do We Need to Install Gulp Globally and Locally
How to Reload or Re-Render the Entire Page Using Angularjs
How to Break/Exit from a Each() Function in Jquery
JavaScript Function Order: Why Does It Matter
Javascript: How to Pass Object by Value
Remove HTML Tags in JavaScript with Regex