Is there a way to have `toHaveBeenCalledWith` match a regular expression? - javascript

I have a function that appends a random number an then calls another function. I want to check that it was called with the text passed in and match any random number. I'd like to be able to pass a Regex without Jest literally matching the Regex. Something like:
const typeFn = jest.fn();
function type (text) {
typeFn(text + Math.random());
})
type('hello')
expect(typeFn).toHaveBeenCalledWith(/hello\d+/)

You can use one of the helper functions in expect instead of an actual value:
expect(typeFn).toHaveBeenCalledWith(expect.stringMatching(/hello\d+/));
Here's a live example: https://repl.it/#marzelin/FrighteningCapitalConferences

Related

How can slice a string within matching characters?

let str = 'axybexaseraszarasxar';
i want string between "a" to next "a" like 'axybexa' string is there any way to take it using substring or slice function of string
You need firstly to detect where the beginning and the end of the substring you want are.
let str = 'axybexaseraszarasxar';
const strBetweenMatches = (st,sep) => {
const first = st.indexOf(sep);
const second = st.indexOf(sep,first+1);
if (second < first) return st.slice(first);
return st.slice(first,second+1)
}
console.log(strBetweenMatches(str,'a')); // your desired output
console.log(strBetweenMatches(str,'j')); // no match
console.log(strBetweenMatches(str,'z')); // only one match
If you want the substring, you can do like this:
let str = 'axybexaseraszarasxar';
let subtring = str.slice(str.indexOf("axybexa") , 7)
If you want to get the new string after slicing off the substring:
let str = 'axybexaseraszarasxar';
let new_string = str.slice(7 , str.length)
It depends on the behaviour that you want.
But one way to do it would be to combine the search() method and the substring() method to clear your specific example.
str.substring(str.search(wordToFind),lengthOfWord);
However, if you want to build it more dynamically there should be some sort of indication as to why you want that specific word. If you always receive it, why even try and break it out of the string?
As an example, IF the search() method doesn't find the word, a -1 will be returned which means you can always check if it exists within the string and if it does, always use it as a separate variable.
Another inefficient way to do it would be to use a for loop and go through each letter in the string individually until you find a succession of the letters you're looking for.
Using the answer from:
split string in two on given index and return both parts
You can always create a split function that allows you to always break up the string on a specific index.
--------------------------------------------------------------
Since the question was just changed, Malarres' answer is the one you want. Use indexOf to find the beginning and end of the substring you're after.

Regex or substring operation to strip out a URL from a keyword onwards [duplicate]

This question already has an answer here:
Reference - What does this regex mean?
(1 answer)
Closed 2 years ago.
I'm struggling to figure out the best way to strip out all the content in a URL from a specific keyword onwards (including the keyword), using either regex or a substring operation. So if I have an example dynamic URL http://example.com/category/subcat/filter/size/1/ - I would like to strip out the /filter/size/1 element of the URL and leave me with the remaining URL as a separate string. Grateful for any pointers. I should clarify that the number of arguments after the filter keyword isn't fixed and could be more than in my example and the number of category arguments prior to the filter keyword isn't fixed either
To be a little safer you could use the URL object to handle most of the parsing and then
just sanitize the pathname.
const filteredUrl = 'http://example.com/category/subcat/filter/test?param1&param2=test';
console.log(unfilterUrl(filteredUrl));
function unfilterUrl(urlString) {
const url = new URL(urlString);
url.pathname = url.pathname.replace(/(?<=\/)filter(\/|$).*/i, '');
return url.toString();
}
You can tweak this a little based on your need. Like it might be the case where filter is not present in the URL. but lets assume it is present then consider the following regex expression.
/(.*)\/filter\/(.*)/g
the first captured group ( can be obtained by $1 ) is the portion of the string behind the filter keyword and the second captured group ( obtained by $2 ) will contain all your filters present after the filter keyword
have a look at example i tried on regextester.com
Use the split() function.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
url='http://example.com/category/subcat/filter/size/1/';
console.log(url.split('/filter')[0]);
Split
The simplest solution that occurs to me is the following:
const url = 'http://example.com/category/subcat/filter/size/1/';
const [base, filter] = url.split('/filter/');
// where:
// base == 'http://example.com/category/subcat'
// filter == 'size/1/'
If you expect more than one occurrence of '/filter/', use the limit parameter of String.split(): url.split('/filter/', 2);
RegExp
The assumption of the above is that after the filter parameter, everything is part of the filter. If you need more granularity, you can use a regex that terminates at the '?', for example. This will remove everything from 'filter/anything/that/follows' that immediately follows a / and until the first query string separator ?, not including.
const filterRegex = /(?<=\/)filter(\/|$)[^?]*/i;
function parseURL(url) {
const match = url.match(filterRegex);
if (!match) { return [url, null, null]; } // expect anything
const stripped = url.replace(filterRegex, '');
return [url, stripped, match[0]];
}
const [full, stripped, filter] = parseURL('http://example.com/category/subcat/filter/size/1/?query=string');
// where:
// stripped == 'http://example.com/category/subcat/?query=string'
// filter == 'filter/size/1/'
I'm sadly not able to post the full answer here, as i'ts telling me 'it looks like spam'. I created a gist with the original answer. In it i talk about the details of String.prototype.match and of JS/ES regex in general including named capture groups and pitfalls. And incude a link to a great regex tool: regex101. I'm not posting the link here in fear of triggering the filter again. But back to the topic:
In short, a simple regext can be used to split and format it (using filter as the keyword):
/^(.*)(\/filter\/.*)$/
or with named groups:
/^(?<main>.*)(?<stripped>\/filter\/.*)$/
(note that the forward slashes need to be escaped in a regex literal)
Using String.prototype.match with that regex will return an array of the matches: index 1 will be the first capture group (so everything before the keyword), index 2 will be everything after that (including the keyword).
Again, all the details can be found in the gist

Javascript regex - getting function name from string

I am trying to get a function name from a string in javascript.
Let's say I have this string:
function multiply($number) {
return ($number * 2);
}
I am using the following regex in javascript:
/([a-zA-Z_{1}][a-zA-Z0-9_]+)\(/g
However, what is selected is multiply(. This is wrong. What I want is the word multiply without the the (, though the regex should keep in mind that the function name must be attached an (.
I can't get this done. How can I make the proper regex for this? I know that this is not something I really should do and that it is quite error sensitive, but I still wanna try to make this work.
Just replace last \) with (?=\()
`function multiply($number) {
return ($number * 2);
}`.match(/([a-zA-Z_{1}][a-zA-Z0-9_]+)(?=\()/g) // ["multiply"]
You can use:
var name = functionString.match(/function(.*?)\(/)[1].trim();
Get anything between function and the first ( (using a non-gredy quantifier *?), then get the value of the group [1]. And finally, trim to remove surrounding spaces.
Example:
var functionString = "function dollar$$$AreAllowedToo () { }";
var name = functionString.match(/function(.*?)\(/)[1].trim();
console.log(name);
Notes:
The characters allowed in javascript for variable names are way too much to express in a set. My answer takes care of that. More about this here
You may want to consider the posibility of a comment between function and (, or a new line too. But this really depends on how you intend to use this regex.
take for examlpe:
function /*this is a tricky comment*/ functionName // another one
(param1, param2) {
}

Javascript Regex after specific string

I have several Javascript strings (using jQuery). All of them follow the same pattern, starting with 'ajax-', and ending with a name. For instance 'ajax-first', 'ajax-last', 'ajax-email', etc.
How can I make a regex to only grab the string after 'ajax-'?
So instead of 'ajax-email', I want just 'email'.
You don't need RegEx for this. If your prefix is always "ajax-" then you just can do this:
var name = string.substring(5);
Given a comment you made on another user's post, try the following:
var $li = jQuery(this).parents('li').get(0);
var ajaxName = $li.className.match(/(?:^|\s)ajax-(.*?)(?:$|\s)/)[1];
Demo can be found here
Below kept for reference only
var ajaxName = 'ajax-first'.match(/(\w+)$/)[0];
alert(ajaxName);
Use the \w (word) pattern and bind it to the end of the string. This will force a grab of everything past the last hyphen (assuming the value consists of only [upper/lower]case letters, numbers or an underscore).
The non-regex approach could also use the String.split method, coupled with Array.pop.
var parts = 'ajax-first'.split('-');
var ajaxName = parts.pop();
alert(ajaxName);
you can try to replace ajax- with ""
I like the split method #Brad Christie mentions, but I would just do
function getLastPart(str,delimiter) {
return str.split(delimiter)[1];
}
This works if you will always have only two-part strings separated by a hyphen. If you wanted to generalize it for any particular piece of a multiple-hyphenated string, you would need to write a more involved function that included an index, but then you'd have to check for out of bounds errors, etc.

Javascript: Reference Array Element using Regex Backreference

Basically, I'm trying to replace parts of a string using elements from an associative array. However, I need to grab elements based on backreferences generated from capturing groups in a replace() expression.
Using the first capturing group, I created this code, which doesn't work:
content = content.replace(/%(\w+)%/g,this.vars["$1"]);
(The regex works fine... I just can't get it to grab the array element.)
How would I go about implementing something like this?
String.replace can take a function as the second argument.
var that = this,
re = /%(\w+)%/g;
content = content.replace(re, function (str, p1)
{
return that.vars[p1];
});

Categories