How do I know if a replacement has occurred in a Javascript replace function?

I have a function that scans a series of lines and replaces them:

var nam = 'Here is a sample string 1/23';

var d   = new Date();
var mon = d.getMonth()+1;
var day = d.getDate();

nam = nam.replace(/\d{1,2}\/\d{1,2}/,day+'/'+mon);

      

However, if no replacements are made (because no regex was found in the string), I want to append day+'/'+mon

to the end of the string.

How can I find out the number of matches of regular expressions?

+3


source to share


3 answers


You have several options.

You can check the match first before doing the replacement, but replacing it means re-evaluating the regex, which, depending on the regex, can be quite expensive:

var re = /\d{1,2}\/\d{1,2}/;

if (re.test(nam))
    nam = nam.replace(re, day+'/'+mon);
else
    nam += day+'/'+mon;

      



Or, as mentioned in the comments, you can replace the string and compare it to the original string - you just need to put it in a temporary variable that costs almost nothing:

var temp = nam.replace(/\d{1,2}\/\d{1,2}/, day+'/'+mon);

if (temp == nam)
    nam += day+'/'+mon;
else
    nam = temp;

      

+1


source


You can check it first:



nam = /\d{1,2}\/\d{1,2}/.test(nam) ? nam.replace(/\d{1,2}\/\d{1,2}/,day+'/'+mon) : nam + day+'/'+mon;

      

0


source


If you want to know if it was replaced and not which part:

temp_nam = nam.replace(/\d{1,2}\/\d{1,2}/,day+'/'+mon);
replaced = (temp_nam == nam) ? false : true;
--- more code ---
nam = temp_nam;

      

Just store the replaced string in a temporary variable and write it after checking in a real variable.

0


source







All Articles