Javascript regexp (match after ":" symbol) - javascript

How to get all text following the symbol ":"?
I have tried:
'prop:bool*'.match(/:(.[a-z0-9]+)/ig)
But it returns [":bool"] not ["bool"].
Update:
I need to use this inside the following expression:
'prop:bool*'.match(/^[a-z0-9]+|:.[a-z0-9]+|\*/ig);
So that the result becomes:
["prop", "bool", "*"]

You could solve this by performing a positive lookbehind action.
'prop:bool*'.match(/^[a-z0-9]+|(?<=:).[a-z0-9]+|\*/ig)
The positive lookbehind is the (?<=:) part of the regex and will here state a rule of must follow ':'.
The result should here be ["prop", "bool", "*"].
Edit:
Original requirements were somewhat modified by original poster to return three groups of answers. My original code, returning one answer, was the following:
'prop:bool*'.match(/(?<=:).[a-z0-9]+/ig)

This is not a pure regex solution since it takes advantage of the String Object with its substring() method, as follows:
var str = 'prop:bool*';
var match = str.match(/:(.[a-z0-9]+)/ig).pop().substring(1,str.length);
console.log(match);
When the match is successful, an array of one element will hold the value :bool. That result just needs to have the bool portion extracted. So, the element uses its pop() method to return the string value. The string in turn uses its substring() method to bypass the ':' and to extract the desired portion, namely bool.
var [a,b,c] = 'prop:bool*'.match(/^([a-z0-9]+)|:(.[a-z0-9]+)|(\*)/ig);
console.log(a,b.substring(1,b.length),c);
To return three groups of data, the code uses capture groups and trims off the colon by using the substring() method of b.

You could simply do:
'prop:bool*'.match(/:(.[a-z0-9]+)/)[1]

If your entire string is of the form you show, you could just use a regex with capture groups to get each piece:
console.log('prop:bool*'.match(/^([a-z0-9]+):(.[a-z0-9]+)(\*)/i).slice(1));

Related

How to get substring between two same characters in JavaScript?

I have a string value as abc:language-letters-alphs/EnglishData:7844val: . I want to extract the part language-letters-alphs/EnglishData, the value between first : and second :. Is there a way to do it without storing each substrings on different vars? I want to do it the ES6 way.
You can do this two ways easily. You can choose what suits you best.
Using String#split
Use split method to get your desired text.
The split() method divides a String into an ordered list of substrings, puts these substrings into an array, and returns the array. The division is done by searching for a pattern; where the pattern is provided as the first parameter in the method's call.
let str = 'abc:language-letters-alphs/EnglishData:7844val:'.split(':')
console.log(str[1]) //language-letters-alphs/EnglishData
Using String#slice
You can use [ Method but in that you have define the exact indexes of the words you want to extract.
The slice() method extracts a section of a string and returns it as a new string, without modifying the original string.
let str = 'abc:language-letters-alphs/EnglishData:7844val:'
console.log(str.slice(4, 38)) //language-letters-alphs/EnglishData
const str = "abc:language-letters-alphs/EnglishData:7844val:"
const relevantPart = str.split(':')[1]
console.log("abc:language-letters-alphs/EnglishData:7844val:".split(":")[1])

Split and grab text before second hyphen

I have the following text string:
test-shirt-print
I want to filter the text string so that it only returns me:
test-shirt
Meaning that everything that comes after the second hyphen should be removed including the hyphen.
I am thinking that the solution could be to split on hyphen and somehow select the two first values, and combine them again.
I am unaware of which functionality is best practice to use here, I also thinking that if it would be possible to use a regular expression in order to be able to select everything before the second hyphen.
You can use split slice and join together to remove everything after the second hyphen
var str = "test-shirt-print";
console.log(str.split("-").slice(0, 2).join('-'))
You can try with String.prototype.slice()
The slice() method extracts a section of a string and returns it as a new string, without modifying the original string.
and String.prototype.lastIndexOf()
The lastIndexOf() method returns the index within the calling String object of the last occurrence of the specified value, searching backwards from fromIndex. Returns -1 if the value is not found.
var str = 'test-shirt-print';
var res = str.slice(0, str.lastIndexOf('-'));
console.log(res);
You can also use split() to take the first two items and join them:
var str = 'test-shirt-print';
var res = str.split('-').slice(0,2).join('-');
console.log(res);

Javascript regex to find a string and extract it from whole string

I have a Javascript array of string that contains urls like:
http://www.example.com.tr/?first=DSPN47ZTE1BGMR&second=NECEFT8RYD
http://www.example.com.tr/?first=RTR22414242144&second=YUUSADASFF
http://www.example.com.tr/?first=KOSDFASEWQESAS&second=VERERQWWFA
http://www.example.com.tr/?first=POLUJYUSD41234&second=13F241DASD
http://www.example.com.tr/?first=54SADFD14242RD&second=TYY42412DD
I want to extract "first" query parameter values from these url.
I mean i need values DSPN47ZTE1BGMR, RTR22414242144, KOSDFASEWQESAS, POLUJYUSD41234, 54SADFD14242RD
Because i am not good using regex, i couldnt find a way to extract these values from the array. Any help will be appreciated
Instead of using regex, why not just create a URL object out of the string and extract the parameters natively?
let url = new URL("http://www.example.com.tr/?first=54SADFD14242RD&second=TYY42412DD");
console.log(url.searchParams.get("first")); // -> "54SADFD14242RD"
If you don't know the name of the first parameter, you can still manually search the query string using the URL constructor.
let url = new URL("http://www.example.com.tr/?first=54SADFD14242RD&second=TYY42412DD");
console.log(url.search.match(/\?([^&$]+)/)[1]); // -> "54SADFD14242RD"
The index of the search represents the parameter's position (with index zero being the whole matched string). Note that .match returns null for no matches, so the code above would throw an error if there's no parameters in the URL.
Does it have to use regex? Would something like the following work:
var x = 'http://www.example.com.tr/?first=DSPN47ZTE1BGMR&second=NECEFT8RYD';
x.split('?first=')[1].split('&second')[0];
Try this regex:
first=([^&]*)
Capture the contents of Group 1
Click for Demo
Code
Explanation:
first= - matches first=
([^&]*) - matches 0+ occurences of any character that is not a & and stores it in Group 1
You can use
(?<=\?first=)[^&]+?
(?<=\?first=) - positive look behind to match ?first=
[^&]+? - Matches any character up to & (lazy mode)
Demo
Without positive look behind you do like this
let str = `http://www.example.com.tr/?first=DSPN47ZTE1BGMR&second=NECEFT8RYD
http://www.example.com.tr/?first=RTR22414242144&second=YUUSADASFF
http://www.example.com.tr/?first=KOSDFASEWQESAS&second=VERERQWWFA
http://www.example.com.tr/?first=POLUJYUSD41234&second=13F241DASD
http://www.example.com.tr/?first=54SADFD14242RD&second=TYY42412DD`
let op = str.match(/\?first=([^&]+)/g).map(e=> e.split('=')[1])
console.log(op)

TS/JS split part of a string from regex match

In the past, I had this regex:
\{(.*?)\}
And entered this string:
logs/{thing:hi}/{thing:hello}
Then I used the following:
console.log(string.split(regex).filter((_, i) => i % 2 === 1));
To get this result:
thing:hi
thing:hello
For irrelevant design reasons, I changed my regex to:
\{.*?\}
But now, when using the same test string and split command, it returns only this:
/
I want it to return this:
{thing:hi}
{thing:hello}
How can I modify the split (or anything else) to do this?
Why not use match?
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match
The match() method retrieves the matches when matching a string against a regular expression.
If you're only interested in returning the two string matches then it's much simpler than using split.
var foo = "logs/{thing:hi}/{thing:hello}";
console.log(foo.match(/{.*?}/g));

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.

Categories