How to get from the string substring after second hyphen? - javascript

If I have three and more hyphens in string I need to get from the string substring after second hyphen.
For example, I have this string:
"someStr1 - someStr2 - someStr3 - someStr4"
As you can see it has 3 hyphens, I need to get from string above substring:
"someStr3 - someStr4"
I know that I need to get the index position of second hyphen and then I can use substring function
But I don't know how to check if there is more then 3 hyphens and how to check thet position is of the second hyphen.

You can use the RegEx (?<=([^-]*-){2}).*
(?<=([^-]*-){2}) makes sure there is 2 - before your match
(?<= ... ) is a positive lookbehind
[^-]* matches anything but a -, 0 or more times
- matches - literally
.* matches anything after those 2 dashes.
Demo.
const data = "someStr1 - someStr2 - someStr3 - someStr4";
console.log(/(?<=([^-]*-){2}).*/.exec(data)[0]);

Split string to array with - and check if array.length > 3 which means at least three - in the string. If true, join the array from index == 2 to the end with - and trim the string.
var text = "someStr1 - someStr2 - someStr3 - someStr4"
var textArray = text.split('-')
if(textArray.length>3){
console.log(textArray.slice(2).join('-').trim())
}

How about something like this:
var testStr = "someStr1 - someStr2 - someStr3 - someStr4";
var hyphenCount = testStr.match(/-/g).length;
if(hyphenCount > 2){
var reqStr = testStr.split('-').slice(-2).join('-');
console.log(reqStr) // logs "someStr3 - someStr4"
}

Related

Regex between last two characters

I have a querstion about simple regex. I need to get between of these characters: - and ~
My string: Champions tour - To Win1 - To Win2 ~JIM FURYK
When I use this: \-([^)]+\~) it is giving as matched this:
To Win1 - To Win2 ~
But I need this:
To Win2 ~JIM FURYK
Is it possible to this?
My regex is here: https://regex101.com/r/fJBLXb/1/
Just add \-([^-)]+\~) - dash to not match
Your \-([^)]+\~) regex matches the leftmost - that is directly followed with one or more chars other than ) (so it matches -, a, §, etc.) and then a ~ char. It does not stop at - chars and thus can match any amount of hyphens.
To match the value after last hyphen you can use
[^\s-][^-]*$
See the regex demo and the regex graph. Details:
[^\s-] - a char other than whitespace and -
[^-]* - zero or more chars other than -
$ - end of string.
See the JavaScript demo:
const text = 'Champions tour - To Win1 - To Win2 ~JIM FURYK';
const match = text.match(/[^\s-][^-]*$/);
if (match) {
console.log(match[0]);
}
You could use match as follows:
var input = "Champions tour - To Win1 - To Win2 ~JIM FURYK";
var output = input.match(/- ([^-]+~.*)$/)[1];
console.log(output);
The regex pattern used above says to match:
- a hyphen
[ ] a single space
( capture what follows
[^-]+ match all content WITHOUT crossing another hyphen
~ ~
.* all remaining content
) stop capture
$ end of the string

Regex to find emoji names with colon and skintone

I'm using EmojiMart for my parser.
I've seen this related question but it seem to be different from mine.
So I need to return the emoji names or :code: for them to be able to decode it.
So example I have this text:
:+1::skin-tone-6::man-pouting:Hello world:skin-tone-
6:lalalalla:person_with_pouting_face: :poop::skin-tone-11: mamamia
:smile: :skin-tone-6:
It should match the whole :+1::skin-tone-6:
and not a separate :+1:, :skin-tone-6:: - only if there’s no space between them. (notice the space between :smile: and :skin-tone-6: )
Conditions:
It should only match the :code::skintone: if skintone is 2-6
If I do str.split(regex) this is my expected result (array):
- :+1::skin-tone-6:
- :man-pouting:
- Hello world
- :skin-tone-6:
- lalalalla
- :person_with_pouting_face:
- :poop:
- :skin-tone-11:
- mamamia
- :smile:
- :skin-tone-6:
You may use String#split() with the
/(:[^\s:]+(?:::skin-tone-[2-6])?:)/
regex. See the regex demo.
Details
: - a colon
[^\s:]+ - 1+ chars other than whitespace and :
(?:::skin-tone-[2-6])? - an optional sequence of
::skin-tone- - a literal substring
[2-6] - a digit from 2 to 6
: - a colon.
JS demo:
var s = ":+1::skin-tone-6::man-pouting:Hello world:skin-tone-6:lalalalla:person_with_pouting_face: :poop::skin-tone-11: mamamia :smile: :skin-tone-6:";
var reg = /(:[^\s:]+(?:::skin-tone-[2-6])?:)/;
console.log(s.split(reg).filter(x => x.trim().length !=0 ));
The .filter(x => x.trim().length !=0 ) removes all blank items from the resulting array. For ES5 and older, use .filter(function(x) { return x.trim().length != 0; }).

Format and replace a string with a regular expression

I have a number that's at least 7 digits long.
Typical examples: 0000123, 00001234, 000012345
I want to transform them so that they become respectively:
01:23, 12:34, 23:45
Which mean replacing the whole string by the last 4 characters and putting a colon in the middle.
I can get the last 4 digits with (\d{4})$
And I can get 2 groups with this: (\d{2})(\d{2})$
With the last option, on a string 0000123 $1:$2 match gives me 00001:23
where I want 01:23
I replace the string like so:
newVal = val.replace(/regex/, '$1:$2');
You need to match the beginning digits with \d* (or with just .* if there can be anything):
var val = "0001235";
var newVal = val.replace(/^\d*(\d{2})(\d{2})$/, '$1:$2');
console.log(newVal);
Pattern details:
^ - start of string
\d* - 0+ digits (or .* will match any 0+ chars other than line break chars)
(\d{2}) - Group 1 capturing 2 digits
(\d{2}) - Group 2 capturing 2 digits
$ - end of string.
As Alex K. said, no need for a regular expression, just extract the parts you need with substr:
val = val.substr(-4, 2) + ":" + val.substr(-2);
Note that when the starting index is negative, it's from the end of the string.
Example:
function update(val) {
return val.substr(-4, 2) + ":" + val.substr(-2);
}
function test(val) {
console.log(val + " => " + update(val));
}
test("0000123");
test("0001234");
test("000012345");
You could throw the first characters away and the replace only the last matched parts.
console.log('00000001234'.replace(/^(.*)(\d{2})(\d{2})$/, '$2:$3'));
Use this regex: ^(\d+?)(\d{2})(\d{2})$:
var newVal = "0000123".replace(/^(\d+?)(\d{2})(\d{2})$/, '$2:$3');
console.log(newVal);

Retrieve BSR and category from string with RegExp

When I parse Amazon products I get this such of string.
"#19 in Home Improvements (See top 100)"
I figured how to retrieve BSR number which is /#\d*/
But have no idea how to retrieve Category which is going after in and end until brackets (See top 100).
I suggest
#(\d+)\s+in\s+([^(]+?)\s*\(
See the regex demo
var re = /#(\d+)\s+in\s+([^(]+?)\s*\(/;
var str = '#19 in Home Improvements (See top 100)';
var m = re.exec(str);
if (m) {
console.log(m[1]);
console.log(m[2]);
}
Pattern details:
# - a hash
(\d+) - Group 1 capturing 1 or more digits
\s+in\s+ - in enclosed with 1 or more whitespaces
([^(]+?) - Group 2 capturing 1 or more chars other than ( as few as possible before th first...
\s*\( - 0+ whitespaces and a literal (.

Regex text/number extraction

Below is regex code for getting the number 6 from my tesetstr. How can i extract the string 'months' from teststr using regex ?
var teststr = '6 months';
var num = /(\d+)\s*month/;
var days = teststr.match(num)[1];
console.log(days);
Currently, (\d+) matches one or more digits capturing them into Group 1 (note you are not using the group at all, so, it is redundant).
You seem to want to only match digits before a space + "month". Use the following regex:
var num = /(\d+)\s*month/;
and then access the captured value with
var days = ($('#infra_time_threshold').text()).match(num)[1] * 30;
^^^
Alternatively, you could use a lookahead right after \d+:
var num = /\d+(?=\s*month)/;
and then just use your .match(num)[0] since Group 0 value will be the whole match.
NOTE: You might want to add a null check before accessing the 0th or 1st index of the match object.

Categories