get only the last match? .match(word) - javascript

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];

Related

Remove part of string that contains a tag

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('<')));

How to get/remove string and the char before from object?

So i have this object of photos, which is value of some hidden input:
53bd570ba13ef.jpg,53bd570c964c3.jpg,53bd570d311c9.jpg,53bd570db8997.jpg.
What i need is to remove last string witch number and the comma before: ,53bd570db8997.jpg.
var dataInput = $('#images'),
imgs = dataInput.val(),
thumbIndex = $(this).parent().index();
//
var _result = imgs.split(',')[thumbIndex];
//
var name = _result.slice(0, _result.indexOf(","));
console.log(name);
The thumbIndex is my photo number/name without the comma: 53bd570db8997.jpg. Can anybody help?
If I understood you right, I'd regexp it:
imgs.replace(new RegExp("," + thumbIndex),"");
imgs should be the string you posted above (the comma-separated one).
If you're sure that thumbIndex contains the last filename, you can get away with this:
var data = '53bd570ba13ef.jpg,53bd570c964c3.jpg,53bd570d311c9.jpg,53bd570db8997.jpg'; // or $('#images').val()
var thumbIndex = '53bd570db8997.jpg';
var result = data.substr(0, data.indexOf(thumbIndex) - 1);
Perhaps you could elaborate a little bit more on what precisely you want to achieve, but I'm going to make an attempt at understanding your question and I will try to give you a solution.
As I understand, you wish to get the last element from a string of values which are delimited by a ',' character.
You could of course split the string and simply get the last element from the array.
var dataInput = $('#images');
var imgs = dataInput.val();
var _result = imgs.split(',');
var thumbnail = _result[_result.length - 1];
console.log(thumbnail);
Here's a JSFiddle to try out: http://jsfiddle.net/WBb5F/1/
If I got you right, you can try lastIndexOf()
var result = data.substr(0, data.indexOf(','));
Fiddle
Using this html
<input type="hidden" value="53bd570ba13ef.jpg,53bd570c964c3.jpg,53bd570d311c9.jpg,53bd570db8997.jpg" id="images" />
To get the last item you can do this:
var dataInput = $('#images'),
imgs = dataInput.val(),
thumbIndex = imgs.split(',').length;
var name = imgs.split(',')[thumbIndex - 1]
console.log(','+ name);
Here is the FIDDLE

JavaScript match-function - Return Array of found elements?

i have a string which has the following format (3,1,Mayer,Jack). I need all 4 elements as own variables. I thought about using JavaScript's match()-function to do this, but i don't know how i can get the 4 elements in variables...
I tried it with this code:
var clickedId = '(3,1,Mayer,Jack)';
var pregId = clickedId.match(/([\d]+,[\d]+,[\w]+,[\w]+)/g);
alert(pregId[0]);
But i get a popup windows with "(3,1,Mayer,Jack)"... I thought about something like this:
var id = pregId[0];
var teamid = pregId[1];
var surname = pregId[2];
var name = pregId[3];
How can i do this?
Thanks!
The match function is matching the whole expression, not pulling out the parts of the whole. So you need to match on each individual element, say with a regex like (\d|\w)+. Here's an example:
var clickedId = '(3,1,Mayer,Jack)';
var pregId = clickedId.match(/((\d|\w)+)/g);
var id = pregId[0];
var teamid = pregId[1];
var surname = pregId[2];
var name = pregId[3];
alert(surname);
Demo: http://jsfiddle.net/Znu7N/
Use individual groups in your regex:
clickedId.match(/([\d]+),([\d]+),([\w]+),([\w]+)/g);
Then the rest should work
Instead your put everything into a single group making the whole expression matched as a single string

One string multiple variables to check with indexOf

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(" ");
}
}

jQuery to parse our a part of a url path

I need to parse long urls and set a variable (category) equal to one of the /folders/ in the path.
For example, a url that is
http://example.com/community/home/whatever.html
I need to set the variable equal to whatever folder path comes after /home/ in that url.
I've got this to alert me with what comes after /community/, but then the url turns to NaN and the link doesnt work. I think I'm not on the right track.
if ($(this.href*='http://example.com/community/')){
var category = url.split("community/");
alert(category[category.length - 1]);
}
Thoughts?
TIA.
You can fetch everything after the "/community/" with a regular expression:
var url = "http://www.example.com/community/whatever";
var category = "";
var matches = url.match(/\/community\/(.*)$/);
if (matches) {
category = matches[1]; // "whatever"
}
Working example here: http://jsfiddle.net/jfriend00/BL4jm/
If you want to get only the next path segment after community and nothing after that segment, then you could use this:
var url = "http://www.example.com/community/whatever/more";
var category = "";
var matches = url.match(/\/community\/([^\/]+)/);
if (matches) {
category = matches[1]; // "whatever"
} else {
// no match for the category
}
Workikng example of this one here:http://jsfiddle.net/jfriend00/vrvbT/
When you do this.href*= you're doing multiplication, and that's why you're getting not-a-number. It multiplies this.href by the string and assigns that to href.
If you mean to test whether the url starts with that string you can do it like this, no need for jQuery:
var start = 'http://example.com/community/';
if (url.substring(0, start.length) === start)){
var category = url.split("community/");
var lastPart = category[category.length - 1];
return lastPart.split("/")[0];
}

Categories