JavaScript match substring after RegExp - javascript

I have a string that look something like
something30-mr200
I would like to get everything after the mr (basically the # followed by mr) *always there is going to be the -mr
Any help will be appreciate it.

You can use a regexp like the one Bart gave you, but I suggest using match rather than replace, since in case a match is not found, the result is the entire string when using replace, while null when using match, which seems more logical. (as a general though).
Something like this would do the trick:
function getNumber(string) {
var matches = string.match(/-mr([0-9]+)/);
return matches[1];
}
console.log(getNumber("something30-mr200"));

var result = "something30-mr200".split("mr")[1];
or
var result = "something30-mr200".match(/mr(.*)/)[1];

Why not simply:
-mr(\d+)
Then getting the contents of the capture group?

What about:
function getNumber(input) { // rename with a meaningful name
var match = input.match(/^.*-mr(\d+)$/);
if (match) { // check if the input string matched the pattern
return match[1]; // get the capturing group
}
}
getNumber("something30-mr200"); // "200"

This may work for you:
// Perform the reg exp test
new RegExp(".*-mr(\d+)").test("something30-mr200");
// result will equal the value of the first subexpression
var result = RegExp.$1;

What about finding the position of -mr, then get the substring from there + 3?
It's not regex, but seems to work given your description?

Related

pretty complex Regex

I did a lot of research, but apparently my Regex skills are not enough to solve this, so I come to humbly ask for advice.
I have a JS var that gets strings similar to this:
"value=8kadctgwqqe0&value=8kaczvfgoyrs&value=8kwkgz2ysm1i"
it doesn't have a fixed lenght. it may return 1 or 20 values, there's no way to know.
As you can see, it returns a big sequence of values that are always between "value=" and "&", except for the last one, that has no "&" in the end.
I need to parse that, and get this in the end:
8kadctgwqqe0
8kaczvfgoyrs
8kwkgz2ysm1i
I don't even know where to start...
Thanks a lot!
personally I would avoid regex for this.
if your string is always in the value=SOMETHING&value=SOMETHINGELSE format use this
string.split("value=").join("").split("&")
according to How to replace all occurrences of a string in JavaScript? its actually quicker to use this over regex also
var string = "value=8kadctgwqqe0&value=8kaczvfgoyrs&value=8kwkgz2ysm1i"
var yourArray = string.split("value=").join("").split("&")
["8kadctgwqqe0", "8kaczvfgoyrs", "8kwkgz2ysm1i"]
You may need to add some tests to ensure the correct format of string if you are not sure about it.
The following RegExp/.filter() should do it:
'value=8kadctgwqqe0&value=8kaczvfgoyrs&value=8kwkgz2ysm1i'.match(/([^=&]+)/g).filter(function(a){return a!='value'});
The .match() will grab the separate query values (and the key names). In order to deal with this, we use .filter() to remove the value results. This will leave it with the correct results.
Sometimes it's better to use regular JavaScript string manipulation (even though this looks like the worst answer)
.filter() is awesome, more info on it here
You can use the following regex:
/(?:^|&)value=([^&]*)/g
regex101 demo
The matches are then stored in the first capture group.
You can now access the capture groups using this method:
var myRegexp = /(?:^|&)value=([^&]*)/g;
var myString = "value=8kadctgwqqe0&value=8kaczvfgoyrs&value=8kwkgz2ysm1i";
match = myRegexp.exec(myString);
while (match != null) {
console.log(match[1]);
match = myRegexp.exec(myString);
}
If you are interested in the keys as well, you can use:
/(?:^|&)([^=&]*)=([^&]*)/g
In that case for each iteration, the key can be found in the first match, and the value in the second one:
var myRegexp = /(?:^|&)([^&=]*)=([^&]*)/g;
var myString = "value=8kadctgwqqe0&value=8kaczvfgoyrs&value=8kwkgz2ysm1i";
match = myRegexp.exec(myString);
while (match != null) {
console.log(match[1]); //key
console.log(match[2]); //value
match = myRegexp.exec(myString);
}
This works as well:
str.match(/value=([^&]*)/g).join("").split('value=').splice(1)

JavaScript String test with array of RegEx

I have some doubts regarding RegEx in JavaScript as I am not good in RegEx.
I have a String and I want to compare it against some array of RegEx expressions.
First I tried for one RegEx and it's not working. I want to fix that also.
function check(str){
var regEx = new RegEx("(users)\/[\w|\W]*");
var result = regEx.test(str);
if(result){
//do something
}
}
It is not working properly.
If I pass users, it doesn't match. If I pass users/ or users/somestring, it is matching.
If I change the RegEx to (usersGroupList)[/\w|\W]*, then it is matching for any string that contains the string users
fdgdsfgguserslist/data
I want to match like if string is either users or it should contain users/something or users/
And also I want the string to compare it with similar regex array.
I want to compare the string str with users, users/something, list, list/something, anothermatch, anothermatch/something. If if it matches any of these expression i want to do something.
How can I do that?
Thanks
Then, you'll have to make the last group optional. You do that by capturing the /something part in a group and following it with ? which makes the previous token, here the captured group, optional.
var regEx = new RegExp("(users)(\/[\w|\W]*)?");
What about making:
the last group optional
starting from beginning of the string
Like this:
var regEx = new RegExp("^(users)(\/[\w|\W]*)?");
Same applies for all the others cases, e.g. for list:
var regEx = new RegExp("^(list)(\/[\w|\W]*)?");
All in One Approach
var regEx = new RegExp("^(users|list|anothermatch)(\/[\w|\W]*)?");
Even More Generic
var keyw = ["users", "list", "anothermatch"];
var keyws = keyw.join("|");
var regEx = new RegExp("^("+keyws+")(\/[\w|\W]*)?");
You haven't made the / optional. Try this instead
(users)\/?[\w|\W]*

javascript regexp match tag names

I can't remember the name of it, but I believe you can reference already matched strings within a RegExp object. What I want to do is match all tags within a given string eg
<ul><li>something in the list</li></ul>
the RegExp should be able to match only the same tags, then I will use a recursive function to put all the individual matches in an array. The regex that should work if I can reference the first match would be.
var reg = /(?:<(.*)>(.*)<(?:FIRST_MATCH)\/>)/g;
The matched array should then contain
match[0] = "<ul><li>something in the list</li></ul>";
match[1] = "ul";
match[2] = ""; // no text to match
match[3] = "li";
match[4] = "something in the list";
thanks for any help
It seems like you mean backreference (\1, \2):
var s = '<ul><li>something in the list</li></ul>';
s.match(/<([^>]+)><([^>]+)>(.*?)<\/\2><\/\1>/)
// => ["<ul><li>something in the list</li></ul>",
// "ul",
// "li",
// "something in the list"]
The result is not exactly same with what you want. But point is that the backreference \1, \2 match the string that was matched by earlier group.
It is not possible to parse HTML using regular expressions (if you're interested in the specifics, it is because HTML parsing requires a stronger type of automaton than a finite state automaton which is what a regular expression can express - look up FSA vs FST for more info).
You might be able to get away with some hack for a specific problem, but if you want to reliably parse HTML using Javascript then there are other ways to do this. Search the web for: parse html javascript and you'll get plenty of pointers on how to do this.
I made a dirty workaround. Still needs work thought.
var str = '<div><ul id="list"><li class="something">this is the text</li></ul></div>';
function parseHTMLFromString(str){
var structure = [];
var matches = [];
var reg = /(<(.+)(?:\s([^>]+))*>)(.*)<\/\2>/;
str.replace(reg, function(){
//console.log(arguments);
matches.push(arguments[4]);
structure.push(arguments[1], arguments[4]);
});
while(matches.length){
matches.shift().replace(reg, function(){
console.log(arguments);
structure.pop();
structure.push(arguments[1], arguments[4]);
matches.push(arguments[4]);
});
}
return structure;
}
// parseHTMLFromString(str); // ["<div>", "<ul id="list">", "<li class="something">", "this is the text"]

RegExp match a single quoted text without quotes - JavaScript

I'm sorry if it is a confusing question. I was trying to find a way to do this but couldn't find it so, if it is a repeated question, my apologies!
I have a text something like this: something:"askjnqwe234"
I want to be able to get askjnqwe234 using a RegExp. You can notice I want to omit the quotes. I was trying this using /[^"]+(?=(" ")|"$)/g but it returns an array. I want a RegExt to return a single string, not an array.
I don't know if it's possible but I do not want to specify the position of the array; something like this:
var x = string.match(/[^"]+(?=(" ")|"$)/g)[0];
Thanks!
Try:
/"([^"]*)"/g
in English: look for " the match and record anything that isn't " till you see another "".
match and exec always return an array or null, so, assuming you have a single double-quoted value and no newlines in the string, you could use
var x;
var str = 'something:"askjnqwe234"';
x = str.replace( /^[^"]*"|".*/g, '' );
// "askjnqwe234"
Or, if you may have other quoted values in the string
x = str.replace( /.*?something:"([^"]*)".*/, '$1' );
where $1 refers to the substring captured by the sub-pattern [^"]* between the ().
Further explanation on request.
Notwithstanding the above, I recommend that you tolerate the array indexing and just use match.
You can capture the information inside quotes like this, assuming it matches:
var x = string.match(/something:"([^"]*)"/)[1];
The memory capture at index 1 is the part inside the double quotes.
If you're not sure it will match:
var match = string.match(/something:"([^"]*)"/);
if (match) {
// use match[1] here
}

How to remove comma from number which comes dynamically in .tpl file

i want to remove comma from a number (e.g change 1,125 to 1125 ) in a .tpl file.
The value comes dynamically like ${variableMap[key]}
var a='1,125';
a=a.replace(/\,/g,''); // 1125, but a string, so convert it to number
a=parseInt(a,10);
Hope it helps.
var a='1,125'
a=a.replace(/\,/g,'')
a=Number(a)
You can use the below function. This function can also handle larger numbers like 123,123,123.
function removeCommas(str) {
while (str.search(",") >= 0) {
str = (str + "").replace(',', '');
}
return str;
};
var s = '1,125';
s = s.split(',').join('');
Hope that helps.
✨ ES2021 ✨ added replaceAll, so no need for regular expression:
const str = '1,125,100.05';
const number = parseFloat(str.replaceAll(",", ""));
You can use Regular Expression to change as it is faster than split join
var s = '1,125';
s = s.replace(/,/g, '');
//output 1125
Incoming value may not always be a string. If the incoming value is a numeric the replace method won't be available and you'll get an error.
Suggest using isNaN to see if numeric, then assume string and do replacement otherwise.
if(isNaN(x)) {
x = parseInt(x.replace(/[,]/g,''));
}
(Not foolproof because 'not number' doesn't prove it is a string, but unless you're doing something very weird should be good enough).
You can also add other symbols to the character group to remove other stray chars (such as currency symbols).

Categories

Resources