If I do regex match for
str = "/mypage/account/info.jsp"
str.match('\/.*\.jsp')
I get entire string but I want to grab only "info"
How can I accomplish using only regex?
First, you can get the text after the last /
/[^/]*$/
and then get the desired result using split
const str = "/mypage/account/info.jsp";
const match = str.match(/[^/]*$/);
const result = match && match[0].split(".")[0];
console.log(result);
only regex
const str = "/mypage/account/info.jsp";
const match = str.match(/[^/]+(?=\.jsp$)/);
console.log(match[0]);
Related
Given the following string:
const myString = "This is my comment content. [~firstName.lastName]";
What is a javascript regex to extract the "firstName" and "lastName"?
What is a javascript regex to extract the content minus the "[~firstName.lastName]"?
I'm rubbish with Regex.
const myString = "This is my comment content. [~firstName.lastName]";
const first = myString.match(/.*\~(.*)\./)[1]
const last = myString.match(/.*\.(.*)]/)[1]
const both = myString.match(/.*\~(.*)\]/)[1]
console.log(first)
console.log(last)
console.log(both)
Here's a good website for regex help
You can try this-
let myString = "This is my comment content. [~firstName.lastName] and the original name is [~John.Doe]";
const regex = /\[~([^\]]+)\.([^\]]+)\]/g;
let match = regex.exec(myString);
const names = [];
while(match !== null) {
names.push({firstName: match[1], lastName: match[2]});
match = regex.exec(myString);
}
// Remove the pattern from the original string.
myString = myString.replace(regex, '');
console.log(names, myString);
This code will find all the matches found for the pattern.
You could target each name separately. match will return the complete match as the first element of the array, and the groupings specified by the ( and ) in the regex as the subsequent elements.
const str = 'This is my comment content. [~firstName.lastName]';
const regex = /\[~(.+)\.(.+)\]/;
console.log(str.match(regex));
Or you could target just the characters within the brackets and then split on the ..
const str = 'This is my comment content. [~firstName.lastName]';
const regex = /\[~(.+)\]/;
console.log(str.match(regex)[1].split('.'));
I know to get a substring between 2 characters we can do something like myString.substring(myString.lastIndexOf("targetChar") + 1, myString.lastIndexOf("targetChar"));
But how would I get a substring if the two targetChar are the same. For example, if I have something like const myString = "/theResultSubstring/somethingElse", how would I extract theResultSubstring in this case?
Do indexOf and lastIndexOf if there are only two characters in your string:
const myString = "/theResultSubstring/somethingElse";
const subString = myString.substring(myString.indexOf("/") + 1, myString.lastIndexOf("/"));
console.log(subString);
Or split it:
const myString = "/theResultSubstring/somethingElse";
const subString = myString.split("/")[1];
console.log(subString);
You could use String#match instead with following regex and positive & negative lookaheads.
const myString = "/theResultSubstring/somethingElse";
const res = myString.match(/(?!\/)\w+(?=\/)/)[0];
console.log(res);
var arr = [];
var str='This is mWORDy word docuWORDment';
if (str.indexOf('WORD') > -1) {
arr.push(Whole word here)
}
This works but I need to push the whole words that contains WORD into the array.
So the result should be this:
arr['mWORDy','docuWORDment'];
How can I do this?
You can split the sentence and use filter to filter the array. Use includes to check if a string contains a certain word.
var str = 'This is mWORDy word docuWORDment';
var arr = str.split(" ").filter(o => o.includes("WORD"));
console.log(arr);
Using String.prototype.match() with a simple regular expression:
const str = 'This is mWORDy word docuWORDment';
const result = str.match(/\w*(WORD)\w*/g);
console.log(result);
You can use this regular expression to capture the matches in a group preceded and suffixed by word boundaries and push it into an array.
const pattern = /\b([A-Za-z]+WORD[A-Za-z]+)\b/gm;
const str = `This is mWORDy word docuWORDment`;
let m;
let matchedArr = [];
while ((m = pattern.exec(str)) !== null) {
// Push the first captured group
matchedArr.push(m[1]);
}
console.log(matchedArr);
I have the following string:
let str = '/user/:username/'
I want to extract replace username with harry with colon removed.
I tried the following:
const regex = /[^:]+(?=:)/g
str.replace(regex, x => console.log(x))
Try: /:\w+/
let str = '/user/:username/'
str.replace(/:\w+/, "harry")
// => "/user/harry/"
let str = '/user/:username/';
let html = str.replace(":username", "harry");
console.log(html);
var str = '/user/:username/';
var newstr = str.replace(/:username/i, "harry");
print(newstr);
hi pal, is this what you are looking for? i found it at https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/String/replace
you can use like that :
let str = '/user/:username/';
str.replace(':username','harry')
// o/p => /user/harry/"
In your regex [^:]+(?=:) you are matching 1+ times not a colon and assert that at the end there should be a colon resulting in a match for /user/
If you want to use the negated character class you could match a colon and then not a forward slash:
:[^\/]+
const str = `/user/:username/`;
const result = str.replace(/:[^\/]+/, "harry");
console.log(result);
I have string in this format:
var a="input_[2][invoiceNO]";
I want to extract "invoiceNo" string. I've tried:
var a="input_[2][invoiceNO]";
var patt = new RegExp('\[(.*?)\]');
var res = patt.exec(a);
However, I get the following output:
Array [ "[2]", "2" ]
I want to extract only invoiceNo from the string.
Note: Input start can be any string and in place of number 2 it can be any number.
I would check if the [...] before the necessary [InvoiceNo] contains digits and is preceded with _ with this regex:
/_\[\d+\]\s*\[([^\]]+)\]/g
Explanation:
_ - Match underscore
\[\d+\] - Match [1234]-like substring
\s* - Optional spaces
\[([^\]]+)\] - The [some_invoice_123]-like substring
You can even use this regex to find invoice numbers inside larger texts.
The value is in capture group 1 (see m[1] below).
Sample code:
var re = /_\[\d+\]\s*\[([^\]]+)\]/g;
var str = 'input_[2][invoiceNO]';
while ((m = re.exec(str)) !== null) {
alert(m[1]);
}
You can use this regex:
/\[(\w{2,})\]/
and grab captured group #1 from resulting array of String.match function.
var str = 'input_[2][invoiceNO]'
var m = str.match(/\[(\w{2,})\]/);
//=> ["[invoiceNO]", "invoiceNO"]
PS: You can also use negative lookahead to grab same string:
var m = str.match(/\[(\w+)\](?!\[)/);
var a="input_[2][invoiceNO]";
var patt = new RegExp('\[(.*?)\]$');
var res = patt.exec(a);
Try this:
var a="input_[2][invoiceNO]";
var patt = new RegExp(/\]\[(.*)\]/);
var res = patt.exec(a)[1];
console.log(res);
Output:
invoiceNO
You could use something like so: \[([^[]+)\]$. This will extract the content within the last set of brackets. Example available here.
Use the greediness of .*
var a="input_[2][invoiceNO]";
var patt = new RegExp('.*\[(.*?)\]');
var res = patt.exec(a);