Last Character of regex match - javascript

I am trying to use a regex to detect a pattern in the current page query string.
For this reason I have the following regex:
var re = new RegExp("([?|&])" + key + "=.*?(&|#|$)", "i");
I am testing it against this input:
http://127.0.0.1:33822/?year=2015&country=Portugal&format=psd
And it works just fine finding the pattern.
What I am really trying to get is the last character index relative to the whole URL.
So for example if I want the index o the last 'd' character:
http://127.0.0.1:33822/?year=2015&country=Portugal&format=ps**d**
In this specific case I would want 60.
Thanks in advance

You can use match.index for that. It will give you where the match exists in the original string.
Then you can use the matche[0].length to find the last character in the match
key='format'
re = new RegExp("([?|&])" + key + "=.*?(&|#|$)", "i");
url='http://127.0.0.1:33822/?year=2015&country=Portugal&format=psd'
match=url.match(re)
console.log(match.index + match[0].length-1) // 60

Related

Javascript Regex match everything after last occurrence of string

I am trying to match everything after (but not including!) the last occurrence of a string in JavaScript.
The search, for example, is:
[quote="user1"]this is the first quote[/quote]\n[quote="user2"]this is the 2nd quote and some url https://www.google.com/[/quote]\nThis is all the text I\'m wirting about myself.\n\nLook at me ma. Javascript.
Edit: I'm looking to match everything after the last quote block. So I was trying to match everything after the last occurrence of "quote]" ? Idk if this is the best solution but its what i've been trying.
I'll be honest, i suck at this Regex stuff.. here is what i've been trying with the results..
regex = /(quote\].+)(.*)/ig; // Returns null
regex = /.+((quote\]).+)$/ig // Returns null
regex = /( .* (quote\]) .*)$/ig // Returns null
I have made a JSfiddle for anyone to have a play with here:
https://jsfiddle.net/au4bpk0e/
One option would be to match everything up until the last [/quote], and then get anything following it. (example)
/.*\[\/quote\](.*)$/i
This works since .* is inherently greedy, and it will match every up until the last \[\/quote\].
Based on the string you provided, this would be the first capturing group match:
\nThis is all the text I\'m wirting about myself.\n\nLook at me ma. Javascript.
But since your string contains new lines, and . doesn't match newlines, you could use [\s\S] in place of . in order to match anything.
Updated Example
/[\s\S]*\[\/quote\]([\s\S]*)$/i
You could also avoid regex and use the .lastIndexOf() method along with .slice():
Updated Example
var match = '[\/quote]';
var textAfterLastQuote = str.slice(str.lastIndexOf(match) + match.length);
document.getElementById('res').innerHTML = "Results: " + textAfterLastQuote;
Alternatively, you could also use .split() and then get the last value in the array:
Updated Example
var textAfterLastQuote = str.split('[\/quote]').pop();
document.getElementById('res').innerHTML = "Results: " + textAfterLastQuote;

Regex in Javascript; string between last and one before last "/"

How to get "foo19" out of the following string
"C:\Users\test\AppData\Roaming\test2\storage\foo19\text.txt"
lastIndexOf does not help in this case either; I just want "foo19" which happens between two "\"s the last "\" and the one before last "\". Is it possible with regex?
Assuming foo19 is always the 2nd to last entry:
var str = "C:\\Users\\test\\AppData\\Roaming\\test2\\storage\\foo19\\text.txt";
var parts = str.split("\\");
var foo19 = parts[parts.length - 2];
Here is a regex that capture foo19 in a group, so access with $1.
.*\\(\w*)\\\w*.txt
The proof is here

javascript replace text at second occurence of "/"

I have this string
"/mp3/mysong.mp3"
I need to do make this string look like this with javascript.
"/mp3/myusername/mysong.mp3"
My guess would be to find second occurrence of "/", then append "myusername/" there or prepend "/myusername" but I'm not sure how to do this in javascript.
Just capture the characters upto the second / symbol and store it into a group. Then replace the matched characters with the characters inside group 1 plus the string /myusername
Regex:
^(\/[^\/]*)
Replacement string:
$1/myusername
DEMO
> var r = "/mp3/mysong.mp3"
undefined
> r.replace(/^(\/[^\/]*)/, "$1/myusername")
'/mp3/myusername/mysong.mp3'
OR
Use a lookahead.
> r.replace(/(?=\/[^/]*$)/, "/myusername")
'/mp3/myusername/mysong.mp3'
This (?=\/[^/]*$) matches a boundary which was just before to the last / symbol. Replacing the matched boundary with /myusername will give you the desired result.
This works -
> "/mp3/mysong.mp3".replace(/(.*?\/)(\w+\.\w+)/, "$1myusername\/$2")
"/mp3/myusername/mysong.mp3"
Demo and explanation of the regex here
use this :
var str = "/mp3/mysong.mp3";
var res = str.replace(/(.*?\/){2}/g, "$1myusername/");
console.log(res);
this will insert the text myusername after the 2nd / .

JavaScript, Dynamic Regex, Replace everything between and including delimiters

Text To Remove:
I am trying to remove a line of text from a file.
Everything between <%'/testStart'%> and <%'/testEnd'%>` including the delimiters.
<%'/testStart'%> Some text with other random characters in between <%'/testEnd'%>
JavaScript:
I have tried this with no luck. Well, at one point I had it working with everything hard coded in the RegExp. But I have tried so many ways I can't remember what I did. Basically I think I am just not escaping something properly.
var p = "/test"; //this is dynamic
var start = "<%'" + p + "Start" + "'%>";
var end = "<%'" + p + "End" + "'%>";
var regex = new RegExp("\\" + start + "[^:]\\" + end);
var newData = data.replace(regex,"");
Expected Result:
Completely remove this line.
<%'/testStart'%> Some text with other random characters in between <%'/testEnd'%>
Any help is much appreciated. Thanks,
Match Inside with a Lazy .*?
Replace your inner section "[^:]\\" with ".*?"
var regex = new RegExp( start + ".*?" + end );
The effect is to match everything up to the end parameter.
Explanation
The star quantifier in .*? is made "lazy" by the ? so that the dot only matches as many characters as needed to allow the next token to match (shortest match). Without the ?, the .* first matches the whole string, then backtracks only as far as needed to allow the next token to match (longest match).

Using regex to search for keywords at the beginning of words only

I have a searching system that splits the keyword into chunks and searches for it in a string like this:
var regexp_school = new RegExp("(?=.*" + split_keywords[0] + ")(?=.*" + split_keywords[1] + ")(?=.*" + split_keywords[2] + ").*", "i");
I would like to modify this so that so that I would only search for it in the beginning of the words.
For example if the string is:
"Bbe be eb ebb beb"
And the keyword is: "be eb"
Then I want only these to hit "be ebb eb"
In other words I want to combine the above regexp with this one:
var regexp_school = new RegExp("^" + split_keywords[0], "i");
But I'm not sure how the syntax would look like.
I'm also using the split function to split the keywords, but I don't want to set a length since I don't know how many words there are in the keyword string.
split_keywords = school_keyword.split(" ", 3);
If I leave the 3 out, will it have dynamic length or just length of 1? I tried doing a
alert(split_keywords.lenght);
But didn't get a desired response
You should use the special word boundary character \b to match the beginning of a word. To create the expression for an arbitrary number of keywords, you can generate it in a loop.
var regex = '';
for(var i = split_keywords.length;i--; ) {
// two slashes are needed to insert `\` literally
regex += "(?=.*\\b" + split_keywords[i] + ")";
}
var regexp_school = new RegExp(regex, "i");
I'm not sure about performance, but you can also consider to use indexOf to test whether a substring is contained in a string.
Update:
If \b does not work for you (because of other "special" characters), and all your words are separated by a white space, you can use
"(?=.*\\s" + split_keywords[i] + ")"
or
"(?=.* " + split_keywords[i] + ")"
But for this to work you have to prepend the text you are searching in with a white space:
" " + textYouSearchIn
or you are write a more complex expression:
"(?=(^|.*\\s)" + split_keywords[i] + ")"
A couple points. First, you need to anchor the regex to the start of the string. Otherwise, if there is no match, there are a LOT of combinations that the regex engine must try before declaring a match failure (it must check all of them, in fact). Second, when splitting the string, use /\s+/ instead of a single space - this prevents getting empty matches in the resulting array in case there are multiple spaces between any keywords. Third, if there are empty strings in the array of keywords, you do not want to add them to the regex. Felix's solution is pretty close to the mark, but does not actually match the string once all the positive lookahead assertions are finished. That said, here's my proposed solution:
var split_keywords = school_keyword.split(/\s+/);
var regex = "^"; // Anchor to start of string.
for (var i = 0, len = split_keywords.length; i < len; ++i) {
if (split_keywords[i]) { // Skip empty keyword strings.
regex += "(?=.*?\\b" + split_keywords[i] + ")";
}
}
regex += ".*$"; // Add ending to actually match the line.
var regexp_school = new RegExp(regex, "i");
I've also changed the greedy quantifier to lazy. This is one case where it is applicable.

Categories

Resources