I need to split a a university course code into prefix and suffix. e.g. CSE1011 into Prefix CSE and Suffix 1011 . Prefix may be 2 or more Alphabets and suffix may be none/ 3 or more. So far I have come up with this RegEx:
/([A-Z]{2,})(?:\s*)([0-9]{3,})?$/g
var courscrCode = 'CSE1011';
var courseRegex = /([A-Z]{2,})(?:\s*)([0-9]{3,})?$/g;
var splitted = courseRegex.exec(courscrCode);
console.log(splitted);
Also tried This. I am getting more match
var courscrCode = 'CSE1011';
var courseRegex = /([A-Z]{2,})(?:\s*)([0-9]{3,})?$/g;
if (courscrCode.match(courseRegex)) {
var splitted = courscrCode.split(courseRegex);
console.log(splitted.length);
if (splitted.length > 1) {
splitted.forEach(function(value, index) {
if ((value != '') && (value != undefined))
console.log(value, index);
});
}
} else {
console.log('course code mangled');
}
I need a solution where i am going to get exactly 2 sub-string prefix and suffix. now I am getting more that 2. I am also open to any other solution
As Terry noted above, MDN states that the array returned by regex will always include the matched text as the first item. The code below will remove the first element.
var courscrCode = 'CSE1011';
var courseRegex = /([A-Z]{2,})(?:\s*)([0-9]{3,})?$/g;
var splitted = courseRegex.exec(courscrCode);
splitted.splice(0,1);
console.log(splitted);
Your splitted array in SECOND sample code is:
["", "CSE", "1011", ""]
If your input text courscrCode is always one course code, you should find prefix in [1] and number in [2]
If input text may be more than just course code to validate, some changes are required.
Note: first empty item in array is all characters before CSE and last item in array is all characters after 1011. It's not whole matched value
var courscrCode = 'CSE1011';
var courseRegex = /([A-Z]{2,})(?:\s*)([0-9]{3,})?$/g;
var prefix = '' ;
var suffix = '' ;
if (courscrCode.match(courseRegex)) {
var splitted = courscrCode.split(courseRegex);
console.log(splitted.length);
if (splitted.length > 1) {
prefix = splitted[1];
suffix = splitted[2];
//or:
splitted.splice(0,1);
splitted.splice(2,1);
console.log(splitted);
}
} else {
console.log('course code mangled');
}
Related
I am trying to replace a string with two sets of patterns. For example,
var pattern1 = '12345abcde/'; -> this is dynamic.
var myString = '12345abcde/hd123/godaddy_item'
my end goal is to get the value between two slashes which is hd123
I have
var stringIneed = myString.replace(pattern1, '').replace('godaddy_item','');
The above codes work but I think there is more elegant solution. Can anyone help me out on this? Thanks a lot!
UPDATE:
To be more clear, the pattern is per environement string. For example,
pattern1 could be something like:
https://myproject-development/item on development environment.
and
https://myproject/item on Production
myString could usually be like
https://myproject/item/hd123/godaddy_item
or
https://myproject-development/item/hd123/godaddy_item
and I need to get 'hd123' in my case.
I'd strongly suggest not using regular expressions for this, especially when simple String and Array methods will easily suffice and be far more understandable, such as:
// your question shows you can anticipate the sections you
// don't require, so put both/all of those portions into an
// array:
var unwanted = ['12345abcde', 'godaddy_item'],
// the string you wish to find the segment from:
myString = '12345abcde/hd123/godaddy_item',
// splitting the String into an array by splitting on the '/'
// characters, filtering that array using an arrow function
// in which the section is the current array-element of the
// array over which we're iterating; and here we keep those
// sections which are not found in the unwanted Array (the index
// an element not found in an Array is returned as -1):
desired = myString.split('/').filter(section => unwanted.indexOf(section) === -1);
console.log(desired); // ["hd123"]
Avoiding Arrow functions, for browsers not supporting ES6 (and having removed the code comments):
var unwanted = ['12345abcde', 'godaddy_item'],
myString = '12345abcde/hd123/godaddy_item',
desired = myString.split('/').filter(function (section) {
return unwanted.indexOf(section) === -1;
});
console.log(desired); // ["hd123"]
Or:
// the string to start with and filter:
var myString = '12345abcde/hd123/godaddy_item',
// splitting the string by the '/' characters and keeping those whose
// index is greater than 0 (so 'not the first') and also less than the
// length of the array-1 (since JS arrays are zero-indexed while length
// is 1-based):
wanted = myString.split('/').filter((section, index, array) => index > 0 && index < array.length - 1);
console.log(wanted); // ["hd123"]
JS Fiddle demo
If, however, the requisite string to be found is always the penultimate portion of the supplied string, then we can use Array.prototype.filter() to return only that portion:
var myString = '12345abcde/hd123/godaddy_item',
wanted = myString.split('/').filter((section, index, array) => index === array.length - 2);
console.log(wanted); // ["hd123"]
JS Fiddle demo.
References:
Array.prototype.filter().
Arrow functions.
String.prototype.split().
You can use
.*\/([^\/]+)\/.*$
Regex Demo
JS Demo
var re = /.*\/([^\/]+)\/.*$/g;
var str = '12345abcde/hd123/godaddy_item';
while ((m = re.exec(str)) !== null) {
document.writeln("<pre>" + m[1] + "</br>" + "</pre>");
}
You can easily do something like this:
myString.split('/').slice(-2)[0]
This will return the item directly, in simple most way.
var myString = 'https://myproject/item/hd123/godaddy_item';
console.log(myString.split('/').slice(-2)[0]); // hd123
myString = 'https://myproject-development/item/hd123/godaddy_item';
console.log(myString.split('/').slice(-2)[0]); // hd123
Try using match() as shown below:
var re = /\/(.*)\//;
var str = '12345abcde/hd123/godaddy_item';
var result = str.match(re);
alert(result[1]);
To say that David's answer will "easily suffice and be far more understandable" is a matter of opinion - this regex option (which includes building up the expression from variables) really couldn't be much simpler:
var pathPrefix = '12345abcde/'; //dynamic
var pathToTest = '12345abcde/hd123/godaddy_item';
var pattern = new RegExp(pathPrefix + '(.*?)\/')
var match = pattern.exec(pathToTest);
var result = (match != null && match[1] != null ? '[' + match[1] + ']' : 'no match was found.'); //[hd123]
What I am trying to do is turn, for example "{{John}}" into "John".
First I am parsing from a string:
var parametrar = content.match(/[{{]+[Aa-Åå]+[}}]/g);
Here regex works fine and it parses as it should. I need to parse the "{}" to find stuff in the string.
But then I'm trying to parse out the "{}" from each "parametrar":
for (var i = 0; i < parametrar.length; i++) {
parametrar = parametrar[i].replace(/[{}]/g, "");
}
When I alert "parametrar" all I get is one "a". I have no idea what I'm doing wrong here, seems it should work.
Try to add greedy matching to maque's answer with using question mark(?).
"{{John}}".replace(/\{\{(.*?)\}\}/g,"$1");
It extracts "John" properly from "{{John}} and Martin}}" input. Otherwise it matches to "John}} and Martin".
You can match the name with braces around and then just use the first capturing group (m[1]):
var re = /\{{2}([a-zA-ZÅå]+)\}{2}/g;
var str = '{{John}}';
if ((m = re.exec(str)) !== null) {
paramterar = m[1];
alert(paramterar);
}
If you have a larger string that contains multiple {{NAME}}s, you can use the code I suggested in my comment:
var re = /\{{2}([a-zA-ZÅå]+)\}{2}/g;
var str = 'My name is {{John}} and {{Vasya}}.';
var arr = [];
while ((m = re.exec(str)) !== null) {
paramterar = m[1];
arr.push(m[1]);
}
alert(arr);
alert(str.replace(/([a-zA-ZÅå])\}{2}/g,"$1").replace(/\{{2}(?=[a-zA-ZÅå])/g, ""))
I have also fixed the character class to only accept English letters + Å and å (revert if it is not the case, but note that [Aa-Åå] is not matching any upper case Englihs letters from B to Z, and matches characters like §.) Please check the ANSI table to see what range you need.
Just do it like that:
"{{John}}".replace(/\{\{(.*)\}\}/g,"$1");
So you are searching for string that have double '{' (these needs to be escaped), then there is something (.*) then again '}' and your output is first match of the block.
Try this:
var parametrar = content.replace(/\{\{([a-åA-Å]+)\}\}/g, "$1");
This gives you a "purified" string. If you want an array, than you can do this:
var parametrar = content.match(/\{\{[a-åA-Å]+\}\}/g);
for (var i = 0, len = parametrar.length; i < len; i++) {
parametrar = parametrar[i].replace(/\{\{([a-åA-Å]+)\}\}/g, "$1");
}
I've written a live filter in javascript that takes a value from a field and hides the rows in a table that do not match.
The RegEx I use for this is very simple: /inputValue/i
Although this works great it only matches characters that are in order. For example:
inputValue = test
string to match = this is a test sentence
This example would match, but if I tried:
inputValue = this sentence
string to match = this is a test sentence
This won't match because the input value is out of order.
How would I go about writing a RegEx that is in order but can skip words?
Here is the loop I currently use:
for (var i=0; i < liveFilterDataArray.length; i++) {
var comparisonString = liveFilterDataArray[i],
comparisonString = comparisonString.replace(/['";:,.\/?\\-]/g, '');
RE = eval("/" + liveFilterValue + "/i");
if (comparisonString.match(RE)) {
rowsToShow.push(currentRow);
}
if(currentRow < liveFilterGridRows.length - 1) {
currentRow++;
} else {
currentRow = 0;
}
}
Many thanks for your time.
Chris
It is recommended to Use RegExp instead of eval.
DEMO
var words = liveFilterValue.split(" ");
var searchArg = (words.length==1)?words:words.join(".*")+'|'+words.reverse().join(".*")
var RE = new RegExp(searchArg,"i");
It will create this.*sentence|sentence.*this/i
remove +'|'+words.reverse().join(".*") if you only want to find this.....sentence and not sentence....this
You could split the input string on spaces and then run the filter sequentially for each word.
I have written a little JQuery / Javascript add on for our form, that takes a single full name input and breaks it into first and last name components. It opens a modal if there are three or more names in the input and asks which combo is correct.
My next step is finding and stripping any suffix that may have been entered such as Jr, Sr, III, etc. I am currently stripping off the last four characters and checking them with indexOf to see if they contain a suffix string (Jr, Sr, III, etc). But each line checks only one possible suffix and I am wondering is there is some js magic that will check multiple suffixs in one line. My current code is below:
var nameVal = $('#name').val();
var suffix = nameVal.slice(-4);
if (suffix.toLowerCase().indexOf(" jr") != -1) {
var nameSplit = nameVal.slice(0, -3).split(" ");
} elseif (suffix.toLowerCase().indexOf(" iii") != -1) {
var nameSplit = nameVal.slice(0, -4).split(" ");
} else {
var nameSplit = nameVal.split(" "); }
I can always do the good old || and keep adding extra (suffix.toLowerCase().indexOf(" jr") != -1) with a different indexOf value, but I am hoping to keep the code more compact if possible, my "little" script is already 3k.
Once I get this sorted the last step will be figuring out how to retain the last name value, so that further down the form when other names are entered and the script is called again it can check to see if the selected last name matches the new entry and bypass the modal pop up.
You can use a regular expression. Try something like this;
nameVal = nameVal.replace(/ (jr|sr|I?II)$/gi, "");
In more detail;
(jr|sr|I?II) = jr or sr or II or III
$ = at the end of line
/i = case insensitive
/g match globally
Probably best to use regexps for this, for example:
var names = [
"Joe Jr.",
"Mark Sr.",
"Loui III",
"Mark Lockering",
];
var suffixRes = [
/Jr\.$/, /Sr\.$/, 'III',
];
$(names).each(function(i, name) {
var str = name;
$(suffixRes).each(function(j, suffixRe) {
str = str.replace(suffixRe, '');
});
console.log(str);
});
Live example:
http://jsfiddle.net/am7QD/
In this case I usually make an array of values, (because I'm not good with regex)
var suffixArr = [' jr',' iii', ' ii'];
//then run a loop
for(var i = 0; i < suffixArr.length;i++){
if(suffixArr[i].toLowerCase().indexOf(suffixArr[i]) != -1){
nameSplit = nameVal.slice(0, - suffixArr[i].length).split(" ");
}
}
I am checking a collection and replacing all
<Localisation container="test">To translate</Localisation>
tags with text.
The next codes does what I want:
var localisationRegex = new RegExp("(?:<|<)(?:LocalisationKey|locale).+?(?:container|cont)=[\\\\]?(?:['\"]|("))(.+?)[\\\\]?(?:['\"]|(")).*?(?:>|>)(.*?)(?:<|<)/(?:LocalisationKey|locale)(?:>|>)", "ig");
match = localisationRegex.exec(parsedData);
while (match != null) {
var localeLength = match[0].length;
var value = match[4];
parsedData = parsedData.substr(0, match.index) + this.GetLocaleValue(value) + parsedData.substr(match.index + localeLength);
match = localisationRegex.exec(parsedData);
}
But, when the the string I replace with, Is longer then the original string, the index/place where it will start to search for the next match, is wrong (to far). This sometimes leads to tags not found.
Setting aside the (important) question as to whether the approach is a good one, if it were me I'd avoid the problem of indexing through the source text by using a function argument to the regex:
var localizer = this;
var result = parsedData.replace(localisationRegex, function(_, value) {
return localizer.GetLocaleValue(value);
});
That will replace the tags with the localized content.