开发者

Javascript Regex after specific string

开发者 https://www.devze.com 2023-04-12 20:44 出处:网络
开发者_C百科I have several Javascript strings (using jQuery). All of them follow the same pattern, starting with \'ajax-\', and ending with a name. For instance \'ajax-first\', \'ajax-last\', \'ajax-e

开发者_C百科I have several Javascript strings (using jQuery). All of them follow the same pattern, starting with 'ajax-', and ending with a name. For instance 'ajax-first', 'ajax-last', 'ajax-email', etc.

How can I make a regex to only grab the string after 'ajax-'?

So instead of 'ajax-email', I want just 'email'.


You don't need RegEx for this. If your prefix is always "ajax-" then you just can do this:

var name = string.substring(5);


Given a comment you made on another user's post, try the following:

var $li = jQuery(this).parents('li').get(0);
var ajaxName = $li.className.match(/(?:^|\s)ajax-(.*?)(?:$|\s)/)[1];

Demo can be found here


Below kept for reference only

var ajaxName = 'ajax-first'.match(/(\w+)$/)[0];
alert(ajaxName);

Use the \w (word) pattern and bind it to the end of the string. This will force a grab of everything past the last hyphen (assuming the value consists of only [upper/lower]case letters, numbers or an underscore).

The non-regex approach could also use the String.split method, coupled with Array.pop.

var parts = 'ajax-first'.split('-');
var ajaxName = parts.pop();
alert(ajaxName);


you can try to replace ajax- with ""


I like the split method @Brad Christie mentions, but I would just do

function getLastPart(str,delimiter) {
  return str.split(delimiter)[1];
}

This works if you will always have only two-part strings separated by a hyphen. If you wanted to generalize it for any particular piece of a multiple-hyphenated string, you would need to write a more involved function that included an index, but then you'd have to check for out of bounds errors, etc.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号