[英]How can I get and replace this in javascript ( jquery?
I need to manipulate a link href which looks like this: 我需要操作如下所示的链接href:
/agents/view/model:Member/ag_start_dateMonth:08/ag_start_dateYear:2012/ag_end_dateMonth:08/ag_end_dateYear:2012 /代理商/视图/型号:会员/ ag_start_dateMonth:08 / ag_start_dateYear:2012 / ag_end_dateMonth:08 / ag_end_dateYear:2012
I need to catch the part: ag_start_dateMonth
and replace the value 08
with a value the user selected through a form. 我需要抓住这一部分: ag_start_dateMonth
并将值08
替换为用户通过表单选择的值。
That means, that I need to find where in the string is this pattern ag_start_dateMonth
and to find the value just after the :
and before the next /
and to replace it with a new value given by the user through form select option. 这意味着,我需要找到模式ag_start_dateMonth
在字符串中的ag_start_dateMonth
并在:
和next /
之前查找值,并将其替换为用户通过表单选择选项提供的新值。
How can I do this? 我怎样才能做到这一点? Please advice, I am quite unsure about regex syntax :-/ 请指教,我不确定regex语法:-/
var s = '/agents/view/model:Member/ag_start_dateMonth:08/ag_start_dateYear:2012/ag_end_dateMonth:08/ag_end_dateYear:2012';
var selected = 10;
s = s.replace(/(ag_start_dateMonth:)([0-9]+)/, '$1' + selected);
This little handy regular expression maintains two matching groups: one that one might call static, and the other which will contain the date that you want to replace. 这个方便的正则表达式维护两个匹配的组:一个可能称为静态的组,另一个会包含要替换的日期。
This should get you going: 这应该可以帮助您:
var s = '/agents/view/model:Member/ag_start_dateMonth:08/ag_start_dateYear:2012/' +
'ag_end_dateMonth:08/ag_end_dateYear:2012';
var newText = 'foo';
alert(s.replace(/(ag_start_dateMonth:)08(\/)/, '$1' + newText + '$2'));
If this input come from a form on the page, you can always "Rebuild" the href instead of search and replace. 如果此输入来自页面上的表单,则始终可以“重建” href,而不是搜索和替换。 Say you have a form you were getting these values from on the page, with jQuery this would be trivial with something like 假设您有一个表单是从页面上获取这些值的,而使用jQuery则很简单,例如
jQuery('#id-of-form button').click( function () {
var start_month = jQuery('#id-of-form select.start-month').val();
var start_year = jQuery('#id-of-form select.start-year').val();
var end_month = jQuery('#id-of-form select.end-month').val();
var end_year = jQuery('#id-of-form select.end-year').val();
jQuery(a#your-link-id).attr('href','/agents/view/model:Member/ag_start_dateMonth:' +
start_month + '/ag_startdateYear:' + start_year + "/ag_end_dateMonth:" +
end_month + '/ag_end_dateYear:' + end_year);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.