regular expression find end of string - javascript

I have troubles with a regular expression.
I want to replace all ocurrences of myData=xxxx& xxxx can change, but always ends with &, except the last ocurrence, when it is myData=xxx.
var data = "the text myData=data1& and &myData=otherData& and end myData=endofstring"
data.replace(/myData=.*?&/g,'newData');
it returns :
the text newData and &newData and end myData=endofstring
which is correct, but how can I detect the last one?

Two things:
You need to assign the result of replace somewhere, which you're not doing in your question's code
You can use an alternation (|) to match either & or end of string
So:
var data = "the text myData=data1& and &myData=otherData& and end myData=endofstring"
data = data.replace(/myData=.*?(?:&|$)/g,'newData');
// ^^^^^^^-- 1 ^^^^^^^-- 2
console.log(data);
Note the use of a non-capturing group ((?:...)), to limit the scope of the alternation.

What about :
data="myData=abc& and linked with something else";
data.replace(/myData=.*?&/g,'newData');
https://jsfiddle.net/ob8c2j9v/

Related

REGEX - after bracket get data until end bracket

I have a string like the following:
SOME TEXT (BI1) SOME MORE TEXT (BI17) SOME FINAL TEXT (BI1234)
Question
I am trying to make a regex to get just the information between the curly brackets, for example the end string would look like:
BI1 BI17 BI1234
I have found this example on stackoverflow which will get the first value BI1, but will ignore the rest after.
Get text between two rounded brackets
this is the REGEX I created from the above link: /\(([^)]+)\)/g but it includes the brackets, I want to remove these.
I am using this website to attempt to solve this query which has a testing window to see if the regex entered works:
http://www.regexr.com
Additional Information
there can be any amount of numbers also, which is why I have given 3 different examples.
this is a continous string, not on seperate lines
thanks for any help on this matter.
While this isn't possible using just regexes, you can do it with string#split and the following regex:
\).*?\(|^.*?\(|\).*?$
Yielding code that looks a bit like this:
function getBracketed(str) {
return str.split(/\).*?\(|^.*?\(|\).*?$/).filter(Boolean);
}
(You need to filter out the empty strings that'll appear at the beginning and end if you do it this way - hence the extra operation).
Regex demo on Regex101
Code demo on Repl.it
If you need to keep all inside parentheses and remove everything else, you might use
var str = "SOME TEXT (BI1) SOME MORE TEXT (BI17) SOME FINAL TEXT (BI1234)";
var result = str.replace(/.*?\(([^()]*)\)/g, " $1").trim();
console.log(result);
If you need to get only the BI+digits pattern inside parentheses, use
/.*?\((BI\d+)\)/g
Details:
.*? - match any 0+ chars other than linebreak symbols
\( - match a (
(BI\d+) - Group 1 capturing BI + 1 or more digits (\d+) (or [^()]* - zero or more chars other than ( and ))
\) - a closing ).
To get all the values as array (say, for later joining), use
var str = "SOME TEXT (BI1) SOME MORE TEXT (BI17) SOME FINAL TEXT (BI1234)";
var re = /\((BI\d+)\)/g;
var res =str.match(re).map(function(s) {return s.substring(1, s.length-1);})
console.log(res);
console.log(res.join(" "));

RegEx - Get All Characters After Last Slash in URL

I'm working with a Google API that returns IDs in the below format, which I've saved as a string. How can I write a Regular Expression in javascript to trim the string to only the characters after the last slash in the URL.
var id = 'http://www.google.com/m8/feeds/contacts/myemail%40gmail.com/base/nabb80191e23b7d9'
Don't write a regex! This is trivial to do with string functions instead:
var final = id.substr(id.lastIndexOf('/') + 1);
It's even easier if you know that the final part will always be 16 characters:
var final = id.substr(-16);
A slightly different regex approach:
var afterSlashChars = id.match(/\/([^\/]+)\/?$/)[1];
Breaking down this regex:
\/ match a slash
( start of a captured group within the match
[^\/] match a non-slash character
+ match one of more of the non-slash characters
) end of the captured group
\/? allow one optional / at the end of the string
$ match to the end of the string
The [1] then retrieves the first captured group within the match
Working snippet:
var id = 'http://www.google.com/m8/feeds/contacts/myemail%40gmail.com/base/nabb80191e23b7d9';
var afterSlashChars = id.match(/\/([^\/]+)\/?$/)[1];
// display result
document.write(afterSlashChars);
Just in case someone else comes across this thread and is looking for a simple JS solution:
id.split('/').pop(-1)
this is easy to understand (?!.*/).+
let me explain:
first, lets match everything that has a slash at the end, ok?
that's the part we don't want
.*/ matches everything until the last slash
then, we make a "Negative lookahead" (?!) to say "I don't want this, discard it"
(?!.*) this is "Negative lookahead"
Now we can happily take whatever is next to what we don't want with this
.+
YOU MAY NEED TO ESCAPE THE / SO IT BECOMES:
(?!.*\/).+
this regexp: [^\/]+$ - works like a champ:
var id = ".../base/nabb80191e23b7d9"
result = id.match(/[^\/]+$/)[0];
// results -> "nabb80191e23b7d9"
This should work:
last = id.match(/\/([^/]*)$/)[1];
//=> nabb80191e23b7d9
Don't know JS, using others examples (and a guess) -
id = id.match(/[^\/]*$/); // [0] optional ?
Why not use replace?
"http://google.com/aaa".replace(/(.*\/)*/,"")
yields "aaa"

Split mulitple part of string in some html div with id

HI i need to split some part of variable value
in my html file i got a dynamic value of variable some thing like this
product/roe_anythin_anything-1.jpg
product/soe_anything_anything-2.jpg
i need to remove the before
/slashpart
and after
_ part
which should return the roe or soe part
i have use a function
<script>
function splitSize(){
$('#splitSize').each(function(index) {
var mystr = $(this).html();
var mystr1 = /product\/(.*)-.*/.exec(mystr);
$(this).html(mystr1[1]);
//$(this).html(mystr1[0]);
});
}
splitSize();
</script>
with which i got roe_anythin_anything successfully i just need to remove now after `
_ part
`
please suggest how can i do this
This is as you asked using split . You can use RegEx to make it simpler
var myStr = 'product/roe-1.jpg' ;
myStr = myStr.split('/')[1];
myStr = myStr.split('-')[0];
Working JS Fiddle
Use regex group capture
var myStr = 'product/roe-1.jpg';
var result = /product\/(.*)-.*/.exec(myStr)[1];
Break down:
/product\/
matches the initial product string and the / character (escaped so its not interpreted as the end of the regex)
The
(.*)
Matches your roe characters and keeps them in a 'capture group' - everything up to but not including the hyphen
Then the hyphen is matched, then anything else.
This returns a 2 element array. Item 0 is the whole string, item 1 is the contents of the capture group.
See How do you access the matched groups in a JavaScript regular expression? for more details

How to with extract url from tweet using Regular Expressions

Ok so i'm executing the following line of code in javascript
RegExp('(http:\/\/t.co\/)[a-zA-Z0-9\-\.]{8}').exec(tcont);
where tcont is equal to some string like 'Test tweet to http://t.co/GXmaUyNL' (the content of a tweet obtained by jquery).
However it is returning, in the case above for example, 'http://t.co/GXmaUyNL,http://t.co/'.
This is frustracting because I want the url without the bit on the end - after and including the comma.
Any ideas why this is appearing? Thanks
First, get rid of the parens in the pattern - they're unnecessary:
RegExp('http:\/\/t.co\/[a-zA-Z0-9\-\.]{8}').exec(tcont);
Second, a regex match returns an array of matching groups - you want the first item in it (the entire match):
var match = RegExp('http:\/\/t.co\/[a-zA-Z0-9\-\.]{8}').exec(tcont);
if(match) {
var result = match[0];
}
The reason you had "a part on the end" is because your result is actually an array - the parens you had in the expression were resulting in an extra matching group (the portion they were around), which would be match[1].
Try this : RegExp('http:\/\/t\.co\/[a-zA-Z0-9\-\.]{8}').exec(tcont);

Remove part of attribute value with jquery or javascript

There is a data parameter for a div that looks as follows:
<div data-params="[possibleText&]start=2011-11-01&end=2011-11-30[&possibleText]">
</div>
I want to remove the from the start through the end of the second date from that data-params attribute. There may or may not be text before the start and after the date after the second date.
How can I accomplish this using javascript or jQuery? I know how to get the value of the "data-params" attribute and how to set it, I'm just not sure how to remove just that part from the string.
Thank you!
Note: The dates will not always be the same.
I'd use a regular expression:
var text = $('div').attr('data-params');
var dates = text.match(/start=\d{4}-\d{2}-\d{2}&end=\d{4}-\d{2}-\d{2}/)[0]
// dates => "start=2011-11-01&end=2011-11-30"
The regular expression is not too complex. The notation \d means "match any digit" and \d{4} means "match exactly 4 digits". The rest is literal characters. So you can see how it works. Finally, that [0] at the end is because javascript match returns an array where the first element is the whole match and the rest are subgroups. We don't have any subgroups and we do want the whole match, so we just grab the first element, hence [0].
If you wanted to pull out the actual dates instead of the full query string, you can create subgroups to match by adding parenthesis around the parts you want, like this:
var dates = text.match(/start=(\d{4}-\d{2}-\d{2})&end=(\d{4}-\d{2}-\d{2})/)
// dates[0] => "start=2011-11-01&end=2011-11-30"
// dates[1] => "2011-11-01"
// dates[2] => "2011-11-30"
Here, dates[1] is the start date (the first subgroup based on parenthesis) and dates[2] is the end date (the second subgroup).
My regex skills aren't that good but this should do it
var txt = "[possibleText&]start=2011-11-01&end=2011-11-30[&possibleText]";
var requiredTxt = txt.replace(/^(.*)start=\d{4}-\d{2}-\d{2}&end=\d{4}-\d{2}-\d{2}(.*)$/, "$1$2");
I'm sure there are better ways to match your string with regex, but the $1 and $2 will put the first group and second group match into your requiredTxt stripping out the start/end stuff in the middle.
Say you have your data-params in a variable foo. Call foo.match as follows:
foo.match("[\\?&]start=([^&#]*)"); //returns ["&start=2011-11-01", "2011-11-01"]
foo.match("[\\?&]end=([^&#]*)"); //returns ["&end=2011-11-30", "2011-11-30"]

Categories