Javascript Regex after specific string - Stack Overflow

I have several Javascript strings (using jQuery). All of them follow the same pattern, starting with &#

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'.

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'.

Share Improve this question edited Oct 11, 2011 at 19:54 cnotethegr8 asked Oct 11, 2011 at 19:29 cnotethegr8cnotethegr8 7,5208 gold badges71 silver badges105 bronze badges 2
  • 1 It should be mentioned whether or not you are using this in a jQuery call, as that places certain limits on the possible solutions to your situation. – Code Jockey Commented Oct 11, 2011 at 19:45
  • 1 @Code Jockey : Sorry about that. It is jQuery. – cnotethegr8 Commented Oct 11, 2011 at 19:53
Add a ment  | 

4 Answers 4

Reset to default 4

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 ment 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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745304114a4621609.html

相关推荐

  • Javascript Regex after specific string - Stack Overflow

    I have several Javascript strings (using jQuery). All of them follow the same pattern, starting with &#

    7小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信