Use only one of the characters in regular expression javascript - javascript

I guess that should be smth very easy, but I'm stuck with that for at least 2 hours and I think it's better to ask the question here.
So, I've got a reg expression /&t=(\d*)$/g and it works fine while it is not ?t instead of &t in url. I've tried different combinations like /\?|&t=(\d*)$/g ; /\?t=(\d*)$|/&t=(\d*)$/g ; /(&|\?)t=(\d*)$/g and various others. But haven't got the expected result which is /\?t=(\d*)$/g or /&t=(\d*)$/g url part (whatever is placed to input).
Thx for response. I think need to put some details here. I'm actually working on this peace of code
var formValue = $.trim($("#v").val());
var formValueTime = /&t=(\d*)$/g.exec(formValue);
if (formValueTime && formValueTime.length > 1) {
formValueTime = parseInt(formValueTime[1], 10);
formValue = formValue.replace(/&t=\d*$/g, "");
}
and I want to get the t value whether reference passed with &t or ?t in references like youtu.be/hTWKbfoikeg?t=82 or similar one youtu.be/hTWKbfoikeg&t=82

To replace, you may use
var formValue = "some?some=more&t=1234"; // $.trim($("#v").val());
var formValueTime;
formValue = formValue.replace(/[&?]t=(\d*)$/g, function($0,$1) {
formValueTime = parseInt($1,10);
return '';
});
console.log(formValueTime, formValue);
To grab the value, you may use
/[?&]t=(\d*)$/g.exec(formValue);
Pattern details
[?&] - a character class matching ? or &
t= - t= substring
(\d*) - Group 1 matching zero or more digits
$ - end of string

/\?t=(\d*)|\&t=(\d*)$/g
you inverted the escape character for the second RegEx.
http://regexr.com/3gcnu

I want to thank you all guys for trying to help. Special thanks to #Wiktor Stribiżew who gave the closest answer.
Now the piece of code I needed looks exactly like this:
/[?&]t=(\d*)$/g.exec(formValue);
So that's the [?&] part that solved the problem.
I use array later, so /\?t=(\d*)|\&t=(\d*)$/g doesn't help because I get an array like [t&=50,,50] when reference is & type and the correct answer [t?=50,50] when reference is ? type just because of the order of statements in RegExp.
Now, if you're looking for a piece of RegExp that picks either character in one place while the rest of RegExp remains the same you may use smth like this [?&] for the example where wanted characters are ? and &.

Related

Removing elements of string before a specific repeated character in it in javascript

I'm trying to remove from my string all elements before an specific character which is repeated several times in this way:
let string = http://localhost:5000/contact-support
thus I´m just trying to remove everything before the third /
having as result:contact_support
for that i just set:
string.substring(string.indexOf('/') + 3);
Bust guess thats not the correct way
Any help about how to improve this in the simplest way please?
Thanks in advance!!!
It seems like you want to do some URL parsing here. JS brings the handful URL utility which can help you with this, and other similar tasks.
const myString = 'http://localhost:5000/contact-support';
const pathname = new URL(myString).pathname;
console.log(pathname); // outputs: /contact-support
// then you can also remove the first "/" character with `substring`
const whatIActuallyNeed = pathname.substring(1, pathname.length);
console.log(whatIActuallyNeed); // outputs: contact-support
Hope This will work
string.split("/")[3]
It will return the sub-string after the 3rd forward slash.
You could also use lastIndexOf('/'), like this:
string.substring(string.lastIndexOf('/') + 1);
Another possibility is regular expressions:
string.match(/[^\/]*\/\/[^\/]*\/(.*)/)[1];
Note that you must escape the slash, since it is the delimiter in regular expressions.
string.substring(string.lastIndexOf('/')+1) will also do the job if you are looking to use indexOf function explicitly.

JS / RegEx to remove characters grouped within square braces

I hope I can explain myself clearly here and that this is not too much of a specific issue.
I am working on some javascript that needs to take a string, find instances of chars between square brackets, store any returned results and then remove them from the original string.
My code so far is as follows:
parseLine : function(raw)
{
var arr = [];
var regex = /\[(.*?)]/g;
var arr;
while((arr = regex.exec(raw)) !== null)
{
console.log(" ", arr);
arr.push(arr[1]);
raw = raw.replace(/\[(.*?)]/, "");
console.log(" ", raw);
}
return {results:arr, text:raw};
}
This seems to work in most cases. If I pass in the string [id1]It [someChar]found [a#]an [id2]excellent [aa]match then it returns all the chars from within the square brackets and the original string with the bracketed groups removed.
The problem arises when I use the string [id1]It [someChar]found [a#]a [aa]match.
It seems to fail when only a single letter (and space?) follows a bracketed group and starts missing groups as you can see in the log if you try it out. It also freaks out if i use groups back to back like [a][b] which I will need to do.
I'm guessing this is my RegEx - begged and borrowed from various posts here as I know nothing about it really - but I've had no luck fixing it and could use some help if anyone has any to offer. A fix would be great but more than that an explanation of what is actually going on behind the scenes would be awesome.
Thanks in advance all.
You could use the replace method with a function to simplify the code and run the regexp only once:
function parseLine(raw) {
var results = [];
var parsed = raw.replace(/\[(.*?)\]/g, function(match,capture) {
results.push(capture);
return '';
});
return { results : results, text : parsed };
}
The problem is due to the lastIndex property of the regex /\[(.*?)]/g; not resetting, since the regex is declared as global. When the regex has global flag g on, lastIndex property of RegExp is used to mark the position to start the next attempt to search for a match, and it is expected that the same string is fed to the RegExp.exec() function (explicitly, or implicitly via RegExp.test() for example) until no more match can be found. Either that, or you reset the lastIndex to 0 before feeding in a new input.
Since your code is reassigning the variable raw on every loop, you are using the wrong lastIndex to attempt the next match.
The problem will be solved when you remove g flag from your regex. Or you could use the solution proposed by Tibos where you supply a function to String.replace() function to do replacement and extract the capturing group at the same time.
You need to escape the last bracket: \[(.*?)\].

Is it possible to cut off the beginning of a string using regex?

I have a string which contains a path, such as
/foo/bar/baz/hello/world/bla.html
Now, I'd like to get everything from the second-last /, i.e. the result shall be
/world/bla.html
Is this possible using a regex? If so, how?
My current solution is to split the string into an array, and join its last two members again, but I'm sure that there is a better solution than this.
For example:
> '/foo/bar/baz/hello/world/bla.html'.replace(/.*(\/.*\/.*)/, "$1")
/world/bla.html
You can also do
str.split(/(?=\/)/g).slice(-2).join('')
> '/foo/bar/baz/hello/world/bla.html'.match(/(?:\/[^/]+){2}$/)[0]
"/world/bla.html"
Without regular expression:
> var s = '/foo/bar/baz/hello/world/bla.html';
> s.substr(s.lastIndexOf('/', s.lastIndexOf('/')-1))
"/world/bla.html"
I think this will work:
var str = "/foo/bar/baz/hello/world/bla.html";
alert( str.replace( /^.*?(\/[^/]*(?:\/[^/]*)?)$/, "$1") );
This will allow for there being possibly only one last part (like, "foo/bar").
You can use /(\/[^\/]*){2}$/ which selects a slash and some content twice followed by the end of the string.
See this regexplained.

Can someone explain what this regex do?

It's part of code where javascript should watch for some price and match if it's lover than required, but i don't understand regex quite well and it's obvious that the error is in there.
So on a website i have price like
<div class="item_price_now"> $ 1,34 </div>
And on javascript part code looks like this
var maxprice = '0.98';
var itemprice = document.getElementByClassName('item_price_now');
var i = 0;
var currentprice = itemprice[i].innerHTML.replace(/\s+/g, ' ');
currentprice = currentprice.substring(2);
if (currentprice > maxprice)
{ do some code }
else
{ do some other code }
But this doesn't work, i assume that part of error is in regex, with this i don't get any values, i tried to change it to something like this
(\S+\w)
And it's outputing something (actually i get output of 1,34 ) but still can't match it with maxprice variable.
Can someone explain me what regex above means or at least point me in some direction. Thanks.
/\s+/g means "match any space/tab character that is repeated one of more times over the entire string".
Hence it's replacing any multiple whitespaces/tabs with a single whitespace.
It seems that your problem is that you use locale strings to describe your value, as you're comparing the string 0.98 (which is casted by JS) with 1,34 (which cannot be casted by JS, as , would be a thousand seperator)

Find and get only number in string

Please help me solve this strange situation:
Here is code:
The link is so - www.blablabla.ru#3
The regex is so:
var id = window.location.href.replace(/\D/, '' );
alert(id);
The regular expression is correct - it must show only numbers ... but it's not showing numbers :-(
Can you please advice me and provide some informations on how to get only numbers in the string ?
Thanks
You're replacing only the first non-digit character with empty string. Try using:
var id = window.location.href.replace(/\D+/g, '' ); alert(id);
(Notice the "global" flag at the end of regex).
Consider using location.hash - this holds just the hashtag on the end of the url: "#42".
You can write:
var id = location.hash.substring(1);
Edit: See Kobi's answer. If you really are using the hash part of things, just use location.hash! (To self: Doh!)
But I'll leave the below in case you're doing something more complex than your example suggests.
Original answer:
As the others have said, you've left out the global flag in your replacement. But I'm worried about the expression, it's really fragile. Consider: www.37signals.com#42: Your resulting numeric string will be 3742, which probably isn't what you want. Other examples: www.blablabla.ru/user/4#3 (43), www2.blablabla.ru#3 (23), ...
How 'bout:
id = window.location.href.match(/\#(\d+)/)[1];
...which gets you the contiguous set of digits immediately following the hash mark (or undefined if there aren't any).
Use the flag /\D/g, globally replace all the instances
var id = window.location.href.replace(/\D/g, '' );
alert(id);
And /\D+/ gets better performance than /\D/g, according to Justin Johnson, which I think because of \D+ can match and replace it in one shot.

Categories

Resources