JS正则表达式匹配字符串末尾的单词

时间:2022-09-19 17:57:47

I have a data-prototype that renders a form. The inputs are rendered as :

我有一个渲染表单的数据原型。输入呈现为:

<input type="text" id="loan_charges_1_date" name="loan[charges][1][date]" class="form-control">
<input type="text" id="loan_charges_1_duration" name="loan[charges][1][duration]" class="form-control">

... next render :

...下一个渲染:

<input type="text" id="loan_charges_2_date" name="loan[charges][2][date]" class="form-control">
<input type="text" id="loan_charges_2_duration" name="loan[charges][2][duration]" class="form-control">

I want to write a JS script to work with dates. So, basically I need a way to catch a input by id that ends with _date or simply date. I think here I need a regular expresion that match _date or date in a string, preferable at the end of that string. Any help, please?

我想写一个JS脚本来处理日期。所以,基本上我需要一种方法来捕获id以_date或date结尾的输入。我想在这里我需要一个与字符串中的_date或date匹配的常规表达式,最好是在该字符串的末尾。有什么帮助吗?

2 个解决方案

#1


1  

You can use regex to match date inside the id attribute with match().

您可以使用正则表达式将id属性中的日期与match()进行匹配。

var bodyText =  document.getElementsByTagName('body')[0].innerHTML;
var ids = bodyText.match(/id="(.*date)"/g);
var idArray = ids.map(x => x = x.split('\"')[1]);
console.log(idArray);

idArray.forEach( x => document.getElementById(x).value = Date());
<input type="text" id="loan_charges_1_date" name="loan[charges][1][date]" class="form-control">
<input type="text" id="loan_charges_1_duration" name="loan[charges][1][duration]" class="form-control">
<input type="text" id="loan_charges_2_date" name="loan[charges][2][date]" class="form-control">
<input type="text" id="loan_charges_2_duration" name="loan[charges][2][duration]" class="form-control">

#2


0  

The regex is /_date$/ /_date$/.test('sample_date') true /_date$/.test('date_sample') false

正则表达式是/ _date $ / /_date$/.test('sample_date')true /_date$/.test('date_sample')false

#1


1  

You can use regex to match date inside the id attribute with match().

您可以使用正则表达式将id属性中的日期与match()进行匹配。

var bodyText =  document.getElementsByTagName('body')[0].innerHTML;
var ids = bodyText.match(/id="(.*date)"/g);
var idArray = ids.map(x => x = x.split('\"')[1]);
console.log(idArray);

idArray.forEach( x => document.getElementById(x).value = Date());
<input type="text" id="loan_charges_1_date" name="loan[charges][1][date]" class="form-control">
<input type="text" id="loan_charges_1_duration" name="loan[charges][1][duration]" class="form-control">
<input type="text" id="loan_charges_2_date" name="loan[charges][2][date]" class="form-control">
<input type="text" id="loan_charges_2_duration" name="loan[charges][2][duration]" class="form-control">

#2


0  

The regex is /_date$/ /_date$/.test('sample_date') true /_date$/.test('date_sample') false

正则表达式是/ _date $ / /_date$/.test('sample_date')true /_date$/.test('date_sample')false