I want to get a sub-string in the cases below:
TruckScaleEntry_DriverId_1535
^------^
EntryCreateForm_TruckScaleEntry_DriverId_1535_SelectWidget_Code
^------^
In the examples above I want the DriverId(It isn't always DriverId, it may change as well) but I never know which pattern I'm dealing with. Actually I got it to work with two regex and two methods(match and replace) together. But I want to know if there is a better - and simpler - way to achieve it.
What I got is:
console.log("TruckScaleEntry_DriverId_1535".match(/(?:.*TruckScaleEntry_)[^_]*/)[0].replace(/^.*_/, ''));
console.log("EntryCreateForm_TruckScaleEntry_DriverId_1535_SelectWidget_Code".match(/(?:.*TruckScaleEntry_)[^_]*/)[0].replace(/^.*_/, ''));
Yeah it is ugly. Can I do something clearer with just one regex and one method?
You could use this regular expression with replace:
var s = 'EntryCreateForm_TruckScaleEntry_DriverId_1535_SelectWidget_Code';
res = s.replace(/^.*?TruckScaleEntry_(.+?)_.*$/, '$1');
document.write(res + '<br>');
// Alternative
res = s.match(/TruckScaleEntry_(.+?)_/)[1];
document.write(res + '<br>');
Results of capturing groups are stored in match objects, which can be accessed by match[1] etc.
JS Demo
var str = 'EntryCreateForm_TruckScaleEntry_DriverId_1535_SelectWidget_Code';
var regex = /TruckScaleEntry_([^_]+)/;
document.writeln(str.match(regex)[1]);
Related
I have a dilemma in using regex as I am very new in using this:
I have the URL below:
var url = https://website.com/something-here/page.html?p=null#confirmation?order=123
My expected result is:
/something-here/page.html #confirmation
It could be a space or a comma or simply combine the two(/something-here/page.html#confirmation)
I can do this using two regex below:
var a= url.match(/som([^#]+).html/)[0];
var b= url.match(/#([^#]+).tion/)[0];
console.log(a,b);
But I would like to have it done as a single regex with the same result.
You can use RegExp's group system to your advantage. Here's a snippet:
var matches = url.match(/(som[^#]+.html).*?(#[^#]+.tion)/);
console.log(matches[1] + " " + matches[2]); // prints /something-here/page.html #confirmation
I combined your two RegExp conditions into one, while enclosing them with parenthesis in the correct areas to create two groups.
That way, you can get the specified group and add a space in between.
Aside the fact that your example url is malformed (you have two search params), therefore not very suitable to work with - I have e proposition:
Why not use the URL object and its properties?
url = new URL("https://website.com/something-here/page.html?p=null#confirmation?order=123");
and precisely grab the properties with explicit syntax as in:
url.pathname; >> "something-here/page.html"
url.hash; >> "#confirmation?order=123"
But in case you explicitly need a RegExp variant
here is one
var url = "https://website.com/something-here/page.html?p=null#confirmation?order=123";
var match = url.match(/\/som.*?html|\#.*?tion/g);
console.log(match.join(" "));
Use each your condition in scope "( )" More details answer try find here
Here is my string:
Organization 2
info#something.org.au more#something.com market#gmail.com single#noidea.com
Organization 3
headmistress#money.com head#skull.com
Also this is my pattern:
/^.*?#[^ ]+|^.*$/gm
As you see in the demo, the pattern matches this:
Organization 2
info#something.org.au
Organization 3
headmistress#money.com
My question: How can I make it inverse? I mean I want to match this:
more#something.com market#gmail.com single#noidea.com
head#skull.com
How can I do that? Actually I can write a new (and completely different) pattern to grab expected result, but I want to know, Is "inverting the result of a pattern" possible?
No, I don't believe there is a way to directly inverse a Regular Expression but keeping it the same otherwise.
However, you could achieve something close to what you're after by using your existing RegExp to replace its matches with an empty string:
var everythingThatDidntMatchStr = str.replace(/^.*?#[^ ]+|^.*$/gm, '');
You can replace the matches from first RegExp by using Array.prototype.forEach() to replace matched RegExp with empty string using `String.ptototype.replace();
var re = str.match(/^.*?#[^ ]+|^.*$/gm);
var res = str;
re.forEach(val => res = res.replace(new RegExp(val), ""));
I have a string of the following form:
data-translate='view-7631b26ea80b1b601c313b15cc4e2ab03faedf30'>Avatar data
It can be in different languages, but in any case I need to get a string which is between the characters ' '
That is, in the example above, I need to get the following string:
view-7631b26ea80b1b601c313b15cc4e2ab03faedf30
Can I do this using the method string.replace(regexp, str) ?
I've highlighted the desired line using the following regular expression:
/'\b(.*)\b'/gm
Now, using the method string.replace I need to delete everything except that...
Got any suggestions?
Use match method.
var data = "data-translate='view-7631b26ea80b1b601c313b15cc4e2ab03faedf30'>Avatar data";
data = data.match(/'\b(.*)\b'/gm)
You have good solid anchor text in either side, so:
var match = /data-translate='([^']+)'/.exec(str);
var substr = match && match[1];
Live Example:
var str = "data-translate='view-7631b26ea80b1b601c313b15cc4e2ab03faedf30'>Avatar data";
var match = /data-translate='([^']+)'/.exec(str);
var substr = match && match[1];
document.body.innerHTML =
"<pre>Got: [" + substr + "]</pre>";
But again, as I said in a comment, using a simple regular expression to extract information from HTML is usually doomed to fail. For instance, you probably don't want to match this:
<p>The string is data-translate='view-7631b26ea80b1b601c313b15cc4e2ab03faedf30'</p>
...and yet, a simple regex solution will do exactly that. To properly handle HTML, you must use a proper HTML parser.
You can also try this one:
/\'([^\']+)\'/gm
I have this string: 2015-07-023. I want to get 07 from this string.
I used RegExp like this
var regExp = /\(([^)]+-)\)/;
var matches = regExp.exec(id);
console.log(matches);
But I get null as output.
Any idea is appreciated on how to properly configure the RegExp.
The best way to do it is to not use RegEx at all, you can use regular JavaScript string methods:
var id_parts = id.split('-');
alert(id_parts[1]);
JavaScript string methods is often better than RegEx because it is faster, and it is more straight-forward and readable. Any programmer can read this code and quickly know that is is splitting the string into parts from id, and then getting the item at index 1
If you want regex, you can use following regex. Otherwise, it's better to go with string methods as in the answer by #vihan1086.
var str = '2015-07-023';
var matches = str.match(/-(\d+)-/)[1];
document.write(matches);
Regex Explanation
-: matches - literal
(): Capturing group
\d+: Matches one or more digits
Regex Visualization
EDIT
You can also use substr as follow, if the length of the required substring is fixed.
var str = '2015-07-023';
var newStr = str.substr(str.indexOf('-') + 1, 2);
document.write(newStr);
You may try the below positive lookahead based regex.
var string = "2015-07-02";
alert(string.match(/[^-]+(?=-[^-]*$)/))
I want to capture some values in a string, THEN return them to the page. Here is an example of the code. As I understand, the .exec should store the values it matches into the array correct? This should return Savage, Betsy. Can someone enlighten me on to what's wrong?
var regex = /\b(Betsy)(Savage)\b/i;
var string = "My friend is Betsy Ann Savage";
var arrayMatch = null;
while(arrayMatch = regex.exec(string)){
document.getElementById("text").innerHTML = arrayMatch[1] + ", " + arrayMatch[0];
}
You don't get any matches like this. You could add .* between (Betsy) and (Savage)...
It sounds like you think \b(Besty)(Savage)\b will match EITHER Besty, OR Savage, but that isn't the case. It's looking for one string where both parts are combined - you might as well try to match \b(BetsySavage)\b. This is because a while yes, you do have two groups separated by parentasis, you have them directly next to each other, so the Regex engine says, 'okay', I'll look for both right next to each other. I think what you really want to do is use | which represents an OR. As in \b(Besty|Savage)\b.