Pattern match to get string between brackets - javascript

I am trying to find whatever string is in between the aggregate() and find(). Below is my code.
var str1 = 'aggregate([{$group:{_id:{state:"$state",city:"$city"},sum:{$sum:"$pop"}}},{$sort:{sum:1}},{$group:{_id:"$_id.state",smallestcity:{$first:"$_id.city"},smallest:{$first:"$sum"},largestcity:{$last:"$_id.city"},largest:{$last:"$sum"}}}])'
var str2 = 'find({awards:{$elemMatch:{award:"Turing Award",year:{$gt:1980}}}}).limit(0)'
var matchPharse = /((.*))/;
var result = str1.match(matchPharse);
console.log(result);
I am getting the result always the whole string instead of
[{$group:{_id:{state:"$state",city:"$city"},sum:{$sum:"$pop"}}},{$sort:{sum:1}},{$group:{_id:"$_id.state",smallestcity:{$first:"$_id.city"},smallest:{$first:"$sum"},largestcity:{$last:"$_id.city"},largest:{$last:"$sum"}}}]
I am searching for something like this

try this pattern instead:
var matchPharse = /((\[.*\]))/;

((\[.*?\]))
You Should use a non greedy expression.

Try the following RegEx:
var matchPharse= /\((.*)\)/g;
Matches any sequence between ().
This is a DEMO.
var str1 = 'aggregate([{$group:{_id:{state:"$state",city:"$city"},sum:{$sum:"$pop"}}},{$sort:{sum:1}},{$group:{_id:"$_id.state",smallestcity:{$first:"$_id.city"},smallest:{$first:"$sum"},largestcity:{$last:"$_id.city"},largest:{$last:"$sum"}}}])'
var str2 = 'find({awards:{$elemMatch:{award:"Turing Award",year:{$gt:1980}}}}).limit(0)'
var matchPharse = /\((.*)\)/;
var result = str1.match(matchPharse);
alert(result);

You just need to escape the outside parentheses. Try:
var matchPharse = /\((.*)\)/;
For just the content inside the parentheses use result[1]

Related

Extract words with RegEx

I am new with RegEx, but it would be very useful to use it for my project. What I want to do in Javascript is this :
I have this kind of string "/this/is/an/example" and I would like to extract each word of that string, that is to say :
"/this/is/an/example" -> this, is, an, example. And then use each word.
Up to now, I did :
var str = "/this/is/a/test";
var patt1 = /\/*/g;
var result = str.match(patt1);
document.getElementById("demo").innerHTML = result;
and it returns me : /,,,,,/,,,/,,/,,,,,
I know that I will have to use .slice function next if I can identify the position of each "/" by using search for instance but using search it only returns me the index of the first "/" that is to say in this case 0.
I cannot find out.
Any Idea ?
Thanks in advance !
Use split()
The split() method splits a String object into an array of strings by separating the string into substrings, using a specified separator string to determine where to make each split.
var str = "/this/is/a/test";
var array = str.split('/');
console.log(array);
In case you want to do with regex.
var str = "/this/is/a/test";
var patt1 = /(\w+)/g;
var result = str.match(patt1)
console.log(result);
Well I guess it depends on your definition of 'word', there is a 'word character' match which might be what you want:
var patt1 = /(\w+)/g;
Here is a working example of the regex
Full JS example:
var str = "/this/is/a/test";
var patt1 = /(\w+)/g;
var match = str.match(patt1);
var output = match.join(", ");
console.log(output);
You can use this regex: /\b[^\d\W]+\b/g, to have a specific word just access the index in the array. e.g result[0] == this
var str = "/this/is/a/test";
var patt1 = /\b[^\d\W]+\b/g;
var result = str.match(patt1);
document.getElementById("demo").innerHTML = result;
<span id="demo"></span>

Javascript Regex: replacing second set of square brackets

I have a string that looks something like this:
"something[something][0][]"
What I need to do is replace the [0] with another number. This is what I've attempted:
var name = nameVar.replace(/[^\[\]]+(?=\]\[[^\]]+\]$)/, "999");
Any help on the regex expression ?
You can use a capturing group for first [...]:
var re = /(\[[^\]]*\])\[[^\]]*\]/;
var str = 'something[something][0][]';
var result = str.replace(re, '$1[999]');
RegEx Demo
Please try:
function myFunction() {
var nameVar = "something[something][0][]";
var name = nameVar.replace(/([^[]+\[[^\]]+\])(\[[^\]]+\])/, '$1[999]');
alert(name);
}
myFunction()

Javascript regex value search

After reading the post here, I tried to get the value by regex as below:
var myString = "<a href='/search.html?id=HDJ&area=ASD&estate=JKG&ppt=3'></a>";
var myRegexp = /&estate=(.*?)(?:\s|$)/g;
var match = myRegexp.exec(myString);
match[1]
The result was JKG&propertytype=3'></a>, but I only want JKG. Strictly speaking I want the value between &estate= and &ppt Could someone suggest how to do that?
Thanks
A Regular Expression:
/&estate=(.*?)&ppt=/g
Note: I wouldn't recommend using regular expressions to parse query strings. It's brittle. Consider if the variables in the query string change order. If that can be the case, I recommend reading - Parse query string in JavaScript.
do:
var myString = "<a href='/search.html?id=HDJ&area=ASD&estate=JKG&ppt=3'></a>";
var myRegexp = /estate=(.*)&ppt=/g;
var match = myRegexp.exec(myString);
console.log( match[1] );
If only the solution is important then you can use the following:
var myString = "<a href='/search.html?id=HDJ&area=ASD&estate=JKG&ppt=3'></a>";
var indx1 = mystring.indexOf("&estate=") + 8;
var indx2 = mystring.indexOf("&ppt");
var neededString = mystring.substring(indx1, indx2);
Just exclude ampersands from the selection:
var myRegexp = /&estate=([^&]+)/g;
You might want to change it to this, in case estate is the first parameter:
var myRegexp = /[\?&]estate=([^&]+)/g;
jsFiddle
Based on your result value, just split it at the ampersand, no new or alternate regex required.
JavaScript:
var myString = "<a href='/search.html?id=HDJ&area=ASD&estate=JKG&ppt=3'></a>";
var myRegexp = /&estate=(.*?)(?:\s|$)/g;
var match = myRegexp.exec(myString);
var value = match[1].split('&')[0];
alert( value );

Search through string with Javascript

Say I have a string like this:
jJKld-xxx-JKl122
Using javascript, how can I get on what's in-between the - characters? In others words, all I need to do is put whatever is xxx into a variable.
Thanks
If the string is always in that format, this will work:
var foo = 'jJKld-xxx-JKl122';
var bar = foo.split('-')[1]; // = xxx
just try it with this simple regex
var str = 'jJKld-xxx-JKl122';
var xxx = str.replace( /^[^\-]*-|-[^\-]*$/g, '' );
You can simply use the following regex to get the result
var myString = "jJKld-xxx-JKl122";
var myRegexp = /(?:^|\s*)-(.*?)-(?:^|\s*)/g;
var match = myRegexp.exec(myString);
alert(match[1]);
See the demo here

Quick Problem - Extracting numbers from a string

I need to extract a single variable number from a string. The string always looks like this:
javascript:change(5);
with the variable being 5.
How can I isolate it? Many thanks in advance.
Here is one way, assuming the number is always surrounded by parentheses:
var str = 'javascript:change(5);';
var lastBit = str.split('(')[1];
var num = lastBit.split(')')[0];
Use regular expressions:-
var test = "javascript:change(5);"
var number = new RegExp("\\d+", "g")
var match = test.match(number);
alert(match);
A simple RegExp can solve this one:
var inputString = 'javascript:change(5);';
var results = /javascript:change\((\d+)\)/.exec(inputString);
if (results)
{
alert(results[1]); // 5
}
Using the javascript:change part in the match as well ensures that if the string isn't in the proper format, you wont get a value from the matches.
var str = 'javascript:change(5);', result = str.match(/\((\d+)\)/);
if ( result ) {
alert( result[1] )
}

Categories

Resources