How to parse functions names from string using javascript? - javascript

I'm looking for a reliable way to get function names from a string. The string values can be something like this:
let str = 'qwe(); asd();zxc()'
//or
let str = 'qwe("foo");asd(1);zxc();'
//etc.
I want to have an array
['qwe', 'asd', 'zxc']
I tried str.split(';') but how do I get rid of parenthesis and anything they can hold? Is there a regexp that will match all symbols on the left of some other symbol?

You can use this simple regex to find function names in .match()
var str = "qwe(); asd();zxc()";
console.log(str.match(/\w+(?=\()/g));

The first case it's fairly simple with regex a simple
[A-Za-z]\w+
would suffice.
on the second case it's a little bit trickier but maybe supressing the match for this
"(.*?)"
maybe a possibility

Related

extract parts of URL string with regex

I have an object value/string that is a url. I need to extract the piece of the url that contains a unique identifier. How can this be done via regex?
Here is the example string:
http://images.example.com/examp/img/uuid/c49eccd1ddf1f4c341bf1d04140sdf7e261ae4014d422376cf9b293e6a8ad7/100/105/1.0
I am trying to extract just what is after uuid/ and before /100
You can do this without having to write a regex. Avoiding regex for simple tasks is usually preferred. Something like this might help:
var str = window.location.href.split( "/uuid/" );
var yourAnswer = str[1].split( "/" );
yourAnswer = str[0];
var identifier=string.split("/")[6];
Simlly take out the stuff between the 5th and the 6th slash.
if the unique ID is /c49eccd1ddf1f4c341bf1d04140sdf7e261ae4014d422376cf9b293e6a8ad7/
you can use this regex '[a-z0-9]{62}' which would mean, a 62 character interval of non-cap letters and numbers.
if you know the length is in between two values, lets say 50-70, you could type it like this: '[a-z0-9]{50,70}'
definetly #jonas-w answer is way better and does not require regexes.

How can I inverse matched result of the pattern?

Here is my string:
Organization 2
info#something.org.au more#something.com market#gmail.com single#noidea.com
Organization 3
headmistress#money.com head#skull.com
Also this is my pattern:
/^.*?#[^ ]+|^.*$/gm
As you see in the demo, the pattern matches this:
Organization 2
info#something.org.au
Organization 3
headmistress#money.com
My question: How can I make it inverse? I mean I want to match this:
more#something.com market#gmail.com single#noidea.com
head#skull.com
How can I do that? Actually I can write a new (and completely different) pattern to grab expected result, but I want to know, Is "inverting the result of a pattern" possible?
No, I don't believe there is a way to directly inverse a Regular Expression but keeping it the same otherwise.
However, you could achieve something close to what you're after by using your existing RegExp to replace its matches with an empty string:
var everythingThatDidntMatchStr = str.replace(/^.*?#[^ ]+|^.*$/gm, '');
You can replace the matches from first RegExp by using Array.prototype.forEach() to replace matched RegExp with empty string using `String.ptototype.replace();
var re = str.match(/^.*?#[^ ]+|^.*$/gm);
var res = str;
re.forEach(val => res = res.replace(new RegExp(val), ""));

Parse string regex for known keys but leave separator

Ok, So I hit a little bit of a snag trying to make a regex.
Essentially, I want a string like:
error=some=new item user=max dateFrom=2013-01-15T05:00:00.000Z dateTo=2013-01-16T05:00:00.000Z
to be parsed to read
error=some=new item
user=max
dateFrom=2013-01-15T05:00:00.000Z
ateTo=2013-01-16T05:00:00.000Z
So I want it to pull known keywords, and ignore other strings that have =.
My current regex looks like this:
(error|user|dateFrom|dateTo|timeFrom|timeTo|hang)\=[\w\s\f\-\:]+(?![(error|user|dateFrom|dateTo|timeFrom|timeTo|hang)\=])
So I'm using known keywords to be used dynamically so I can list them as being know.
How could I write it to include this requirement?
You could use a replace like so:
var input = "error=some=new item user=max dateFrom=2013-01-15T05:00:00.000Z dateTo=2013-01-16T05:00:00.000Z";
var result = input.replace(/\s*\b((?:error|user|dateFrom|dateTo|timeFrom|timeTo|hang)=)/g, "\n$1");
result = result.replace(/^\r?\n/, ""); // remove the first line
Result:
error=some=new item
user=max
dateFrom=2013-01-15T05:00:00.000Z
dateTo=2013-01-16T05:00:00.000Z
Another way to tokenize the string:
var tokens = inputString.split(/ (?=[^= ]+=)/);
The regex looks for space that is succeeded by (a non-space-non-equal-sign sequence that ends with a =), and split at those spaces.
Result:
["error=some=new item", "user=max", "dateFrom=2013-01-15T05:00:00.000Z", "dateTo=2013-01-16T05:00:00.000Z"]
Using the technique above and adapt your regex from your question:
var tokens = inputString.split(/(?=\b(?:error|user|dateFrom|dateTo|timeFrom|timeTo|hang)=)/);
This will correctly split the input pointed out by Qtax mentioned in the comment: "error=user=max foo=bar"
["error=", "user=max foo=bar"]

How to match a specific regular expression?

I am having a hard time understanding how to match a certain regular expression using javascripts match() function. I have a field in a table stored in the following format:
CH-01-Feb-13-1. I want to be able to grab the date without the dashes, i.e. 01-Feb-13. I was trying to figure out how to combine with ^- or . but not sure how to do it.
So you want the regular expression?
Something like
^\w{2}-(\d{2}-\w{3}-\d{2}).*?$
You can see the explanation here: http://www.regexper.com/ Just copy and paste the expression.
Example with Javascript
var r = /^\w{2}-(\d{2}-\w{3}-\d{2}).*?$/i
var groups = "CH-01-Feb-13-1".match(r);
console.log(groups);
If you are not comfortable with Regex then you can use something like this.
var str = 'CH-01-Feb-13-1';
str = str.replace('CH-','');
str = str.split('-');
str.pop();
console.log(str.join('-'));

Javascript regex expression to replace multiple strings?

I've a string done like this: "http://something.org/dom/My_happy_dog_%28is%29cool!"
How can I remove all the initial domain, the multiple underscore and the percentage stuff?
For now I'm just doing some multiple replace, like
str = str.replace("http://something.org/dom/","");
str = str.replace("_%28"," ");
and go on, but it's really ugly.. any help?
Thanks!
EDIT:
the exact input would be "My happy dog is cool!" so I would like to get rid of the initial address and remove the underscores and percentage and put the spaces in the right place!
The problem is that trying to put a regex on Chrome "something goes wrong". Is it a problem of Chrome or my regex?
I'd suggest:
var str = "http://something.org/dom/My_happy_dog_%28is%29cool!";
str.substring(str.lastIndexOf('/')+1).replace(/(_)|(%\d{2,})/g,' ');
JS Fiddle demo.
The reason I took this approach is that RegEx is fairly expensive, and is often tricky to fine tune to the point where edge-cases become less troublesome; so I opted to use simple string manipulation to reduce the RegEx work.
Effectively the above creates a substring of the given str variable, from the index point of the lastIndexOf('/') (which does exactly what you'd expect) and adding 1 to that so the substring is from the point after the / not before it.
The regex: (_) matches the underscores, the | just serves as an or operator and the (%\d{2,}) serves to match digit characters that occur twice in succession and follow a % sign.
The parentheses surrounding each part of the regex around the |, serve to identify matching groups, which are used to identify what parts should be replaced by the ' ' (single-space) string in the second of the arguments passed to replace().
References:
lastIndexOf().
replace().
substring().
You can use unescape to decode the percentages:
str = unescape("http://something.org/dom/My_happy_dog_%28is%29cool!")
str = str.replace("http://something.org/dom/","");
Maybe you could use a regular expression to pull out what you need, rather than getting rid of what you don't want. What is it you are trying to keep?
You can also chain them together as in:
str.replace("http://something.org/dom/", "").replace("something else", "");
You haven't defined the problem very exactly. To get rid of all stretches of characters ending in %<digit><digit> you'd say
var re = /.*%\d\d/g;
var str = str.replace(re, "");
ok, if you want to replace all that stuff I think that you would need something like this:
/(http:\/\/.*\.[a-z]{3}\/.*\/)|(\%[a-z0-9][a-z0-9])|_/g
test
var string = "http://something.org/dom/My_happy_dog_%28is%29cool!";
string = string.replace(/(http:\/\/.*\.[a-z]{3}\/.*\/)|(\%[a-z0-9][a-z0-9])|_/g,"");

Categories