Javascript string replace using regex expression - javascript

Give the following string:
http://foobar.com/trusted/123/views/AnalyticsInc
..where 123 will be a number anywhere between 0 and 9999999, I need to be able to dynamically replace said value with a different value
I assume the best way to approach this is to do a string.replace with some sort of regex pattern, since we can count on the fact that "/trusted/" and "/views/" will always surround the value that needs to be swapped out.
var foo='http://foobar.com/trusted/123/views/AnalyticsInc';
var newvalue=654321;
magic(); //magic happens here
console.log(foo); //returns http://foobar.com/trusted/654321/views/...etc
But my regex kung-fu is so weak I cannot defeat a kitten. Can someone give me a hand? Or if there's a better approach, I'd love to learn it. Thanks!

It will replace the first occurrence of number from 0 to 9999999 in foo string:
foo = foo.replace(/\d{1,7}/, newvalue);
DEMO: http://jsfiddle.net/D4teZ/

Related

Regex that only matches when 4 specific words were found

As the title says, I need a Regex to check if a string has this four words (Update, Rollback, Skip, Not Now) and only return them if all of them are present, if not it doesn’t return anything.
Here is an example:
{"Update":"iVBORw0KGgo","Rollback":"iVBORw0KGgo","Skip":"iVBORw0KGgo","Not Now":"iVBORw0KGgo"}
In this case, it should return [Update, Rollback, Skip, Not Now]
{"Update":"iVBORw0KGgo","Skip":"iVBORw0KGgo","Not Now":"iVBORw0KGgo"}
In this case, it shouldn’t return any value
I tried to create one by myself but my knowledge of Regex is very basic:
(Update|Rollback|Skip|Not Now)
Thanks in advance!
EDIT
I noticed that Regex might not be the best way to achieve this.
Use this:
^(?=.*"Update"\s*:)(?=.*"Rollback"\s*:)(?=.*"Skip"\s*:)(?=.*"Not Now"\s*:)
(?=...) means that if you lookahead, you find this pattern.
So an empty match will return as soon as we find all these 4 patterns.
demo
As an alternative to regex, you can use JSON.parse to parse the string into an object and Object.keys to get the properties:
const str = `{"Update":"iVBORw0KGgo","Rollback":"iVBORw0KGgo","Skip":"iVBORw0KGgo","Not Now":"iVBORw0KGgo"}`;
const keys = Object.keys(JSON.parse(str))
const result = keys.sort().toString() == "Not Now,Rollback,Skip,Update" ? keys : "";
console.log(result)
While regex is clearly not a good tool for the job,
you can do something like this:
re.match("(?=.*Update.*)(?=.*Skip.*)",string)
"(?=WORD)" matches if the expression follows, but doesn't consume any of the string.
Of course, complete the regex by all 4 words that you want similarly.
Also notice that regex by itself doesn't return anything. You need to code for this.

Use only one of the characters in regular expression 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 &.

Matching and returning a regex between two values

I am trying to get the values from a string using regex, the value is that of the text between tt=" and "&
So, for example, "tt="Value"&" I would only want to get the word "Value" out of this.
So far I have this: /tt=.*&/ which gives me "tt=Value"&, Then, to get the value I am thinking to split the match on = and remove the 2 characters from the end. I feel though, that this would be an awful way to do this and would like to see if it could be done in the regex?
You're on the right track for matching the entire context inside of the string, but you want to use a capturing group to match/capture the value between the quotes instead of splitting on = and having to remove the two quote chars.
var r = 'tt="Value"&'.match(/tt="([^"]*)"/)[1];
if (r)
console.log(r); //=> "Value"
I know this isn't really the answer you are looking for since it doesn't involve regex but it's the way I usually do it.
strvariable = strvariable.Remove(0,strvariable.IndexOf("=") + 2);
strvariable = strvariable.Remove(strvariable.IndexOf("\""), strvariable.Length - strvariable.IndexOf("\""));
this would give you the result you were looking for which is Value in this instance.

Regex equivalent to str.substr(0, str.indexOf('foo'))

Given this string:
var str = 'A1=B2;C3,D0*E9+F6-';
I would like to retrieve the substring that goes from the beginning of the string up to 'D0*' (excluding), in this case:
'A1=B2;C3,'
I know how to achieve this using the combination of the substr and indexOf methods:
str.substr(0, str.indexOf('D0*'))
Live demo: http://jsfiddle.net/simevidas/XSu22/
However, this is obviously not the best solution since it contains a redundancy (the str name has to be written twice). This redundancy can be avoided by using the match method together with a regular expression that captures the substring:
str.match(/???/)[1]
Which regular expression literal do we have to pass into match to ensure that the correct substring is returned?
My guess is this: /(.*)D0\*/ (and that works), but my experience with regular expressions is rather limited, so I'm going to need a confirmation...
Try this:
/(.*?)D0\*/.exec(str)[1]
Or:
str.match(/(.*?)D0\*/)[1]
DEMO HERE
? directly following a quantifier makes the quantifier non-greedy (makes it match minimum instead of maximum of the interval defined).
Here's where that's from
/^(.+?)D0\*/
Try it here: http://rubular.com/r/TNTizJLSn9
/^.*(?=D0\*)/
more text to hit character limit...
You can do a number-group, like your example.
/^(.*?)foo/
It mean somethink like:
Store all in group, from start (the 0)
Stop, but don't store on found foo (the indexOf)
After that, you need match and get
'hello foo bar foo bar'.match(/^(.*?)foo/)[1]; // will return "hello "
It mean that will work on str variable and get the first (and unique) number-group existent. The [0] instead [1] mean that will get all matched code.
Bye :)

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