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(" ");
}
}
Related
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');
}
I have a regex to get #user from a textarea. When user type something with # I get it.
My problem is, I want to get just the last match, not all of them.
eg:
user type:
#josh and #marie = want to show #marie
#josh loves #marie and #anne = show #anne
my code is showing like this:
#josh,#marie,#anne
Can I get just the last #something entry? (while user is typing)
var word=/#(\w+)/ig;
$("#comment").on("keyup",function() {
var content = $(this).val();
var name = content.match(word);
var dataString = name;
if(name.length > 0) {
$("#result").text(name);
}
return false();
});
html
<textarea id=comment>#josh and #marie</textarea>
<div id=result></div>
https://jsfiddle.net/dcs5pat8/ (press on textarea)
Besides getting all matches and obtain the last one, you can use capture groups to get the last match:
var word=/.*(#\w+)/i;
var name = content.match(word)[1];
Or using exec, the whole would look like:
var word=/.*(#\w+)/i;
$("#comment").on("input",function() { //changed keyup to input
var content=$(this).val();
var match = word.exec(content);
if(match){
$("#result").text(match[1]);
}
});
Fiddle
PS, if your goal is a more generic approach and you need to switch between getting all words and a single one, I'd recommend keeping the global match and getting the last as in Jonas' answer.
My suggestion is that you show only the last entry of your results.
You can do that by changing the line:
var name = content.match(word);
to
var names = content.match(word);
var name = names[names.length - 1];
On more detail, what this does is it gets all the results from your regex, then it attributes the last item of the array to the name variable.
Hope this was helpful.
You can simply select or pop the last match in the array of match returned by .match()
var word=/#(\w+)/ig;
$("#comment").on("keyup",function() {
var content=$(this).val();
var matches = content.match(word);
var lastmatch = matches.pop();
//IF YOU NEED TO KEEP INTACT THE VAR MATCHES
//var lastmatch = matches[matches.length - 1];
if(name.length>0){
$("#result").text(lastmatch);
}
return false();
});
JSFiddle
Use this regex '/#(\w+)$/ig' insted of '/#(\w+)/ig'.
And then your code will run like a charm. ;)
var word=/#(\w+)$/ig;
$("#comment").on("keyup",function() {
var content=$(this).val();
var name = content.match(word);
var dataString = name;
if(name.length>0){
$("#result").text(name);
}
return false();
});
See it hear https://jsfiddle.net/dcs5pat8/1/
I do like the answer where you take your list with all of the #names,#name1,#name2 and just split off the last one, but here it is in just one step
//split on #something
//the penultimate item is our target
//if there is < 2 items there weren't any #somethings so return ''
user = (split = "testing #charlie testing".split(/(#[^ ]*)/)).length > 1 ? split.splice(-2,1)[0] : '';
https://jsfiddle.net/ek19h0fb/1/
To have only one line you can do
var name = content.match(word).reverse()[0];
I'm doing a tracking application for my company and I really need your help
I've got some strings that display it wrong
I'll get the postcode/zipcode and the city name and the "function" (for example distrubition basis)
The string I get is something like that (it's swiss and the format is postcode cityname function)
place = "5506 MägenwilDistributionsbasis";
now postcode is "5506"
cityname is "Mägenwil"
function is "Distributionsbasis"
my question is how can I split the cityname and function (for this example now)?
is it possible to do it with regex or an if statement?
You can split the string using the following regexp:
var myString = "5506 MägenwilDistributionsbasis";
var units = /(\d+ )([A-Z][^A-Z]+)(.+)/g.exec(myString);
Check out contents of array units: there you see units[0] is the whole string, and units[1], units[2], units[3] are what you need.
Note According to comments I must say, it's just a draft for possible solution to let you understand how to start working on the problem in JS. So when you will test your application with more complicated city names and function names in the "magic string", try to figure out what regexp fits your purposes perfectly, because ([A-Z][^A-Z]+) definitly will not match all the known city names.
You could implement that in the most primitive way. Something like this:
place = "5506 MägenwilDistributionsbasis";
var codeAndNameAndFunction = place.split(" ");
var code = codeAndNameAndFunction[0];
var nameAndFunction = codeAndNameAndFunction[1];
var startOfTheFunction;
for (var i = 1, len = nameAndFunction.length; i < len; i++) {
myCharacter = nameAndFunction.charCodeAt(i);
if (myCharacter >= 65 && myCharacter <= 90) {
startOfTheFunction = i;
break;
}
}
var name = nameAndFunction.slice(0, startOfTheFunction);
var functionName = nameAndFunction.slice(startOfTheFunction,nameAndFunction.length);
This is a slight modification of Florian Peschka's answer:
You can split the string using the following regexp:
var myString = "5506 Yverdon-les-BainsDistributionsbasis";
var units = /(\d+ )(.+)([A-Z][^A-Z]+)/g.exec(myString);
Check out contents of array units: there you see units[0] is the whole string, and units[1], units[2], units[3] are what you need.
Note that this will only work if the "function" name is always in the form of Capital Letter followed by Non-capital letters.
I have a variable in JavaScript that holds the below value:
<label>AAA</label>
I need just the AAA. I try to replace the characters but it is failing. Would someone please suggest the best approach?
var company="<label>AAA</label>";// I am getting this value from element
var rx = new RegExp("((\\$|)(([1-9]\\d{0,2}(\\,\\d{3})*|([1-9]\\d*))(\\.\\d{2})))|(\\<)*(\\>)");
var arr = rx.exec(company);
var arr1 = company.match(rx);
if (arr[1] != null) {
var co = arr[1].replace(",", "");
}
}
As you say you need only AAA, consider the below code.
I have taken a substring between the first '>' character in the string company, added 1 to that and the last < character. However, if the company var contains more of such < or >, you could go for a regex approach.
var company="<label>AAA</label>";
alert(company.substring(company.indexOf('>')+1, company.lastIndexOf('<')));
I generated the following code through a website. What I am looking for is that the script scans through a text variable against a set of keywords, and if it finds any of the keywords, it passes it to a variable. And if two keywords are found, both are joined by a hyphen and passed to a variable. I also need to set the "var str" dynamically. For instance, "var str == VAR10." VAR10 will have a dynamic text to be searched for keywords.
var re = /Geo|Pete|Rob|Nick|Bel|Sam|/g;
var str = 'Sam maybe late today. Nick on call. ';
var m;
if ((m = re.exec(str)) !== null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
}
In the above code, Sam and Nick are two keywords that I want hyphenated and passed to VAR10.
If two keywords are found, both are joined by a hyphen and passed to a
variable
Try this update to your original code for clarity:
var re = /Geo|Pete|Rob|Nick|Bel|Sam/g;
var str = 'Sam maybe late today. Nick on call. ';
var m;
var VAR10 = ""; // holds the names found
if ((m = re.exec(str)) !== null) {
var name1 = m;
if ((m = re.exec(str)) !== null) {
var name2 = m;
// Two names were found, so hyphenate them
// Assign name1 + "-" + name2 to the var that you want
VAR10 = name1 + "-" + name2;
} else {
// In the case only one name was found:
// Assign name1 to the var that you want
VAR10 = name1;
}
}
Note, change
var re = /Geo|Pete|Rob|Nick|Bel|Sam|/g;
to
var re = /Geo|Pete|Rob|Nick|Bel|Sam/g;
Here is an updated demo: http://jsfiddle.net/7zg2hnt6/1/
You can "capture" names with parenthesis:
/(Geo|Pete|Rob|Nick|Bel|Sam)/g
A sample: https://regex101.com/r/eK5hY2/1
To return the first two names found in hyphenated fashion:
str.match(re) . slice(0, 2) . join('-')
You have an extra | at the end of your regexp, which is likely to result in matches on an empty string. Remove it.
I also need to set the "var str" dynamically. For instance, "var str == VAR10." VAR10 will have a dynamic text to be searched for keywords.
var str == VAR10 is invalid syntax. I'll assume you mean var str = VAR10;. That's just a plain old variable assignment. All assignments in JS are "dynamic" by definition and happen at run-time. This would seem to have nothing to do with your specific problem.
Your code is almost doing what you want.
First you need to capture your matches, then join them.
http://jsfiddle.net/c6tjk21d/1/
var re = /(Geo|Pete|Rob|Nick|Bel|Sam)/g;
var str = 'Sam maybe late today. Nick on call. ';
var VAR10 = str.match(re).join('-')
console.log(VAR10);
I don't think you want to use exec because it maintains state and I've found it to be unintuitive. For example, in order to get more than one match with the code you've written, you'll need to loop through resulting on exec. Check out MDN for examples if you're interested. I almost always prefer match().