简体   繁体   中英

Reusing Javascript code without repasting it again and again

I have the below code, which looks for the text "UID" and changes it to "UID *"

On my page, there are other terms such as "description", "score" and so on. I would also like to append * to these as well - is there a tidy way to get the below code to edit those as well? Only way I know is to repeat this code block again and again?

    <script type="text/javascript">
    //Mark UID as Mandatory
    var CFN = "UID";
    $(document).ready(ExecuteOrDelayUntilScriptLoaded(MainFunction, "sp.js"));
    function MainFunction() {
        Mandatory();
    }
    function Mandatory(){
    $(".ms-accentText").each(function() {
    var text = $(this).text(); 
    $(this).text(text.replace(CFN, 'UID *'));
    });
    }    
    </script>

EDIT. I tried the below reply, but this didn't work for me, I have got this code now, but again, doesn't seem to work (its trying to add a * onto "UID" and "Description" where found using a multi variable;

    <script type="text/javascript">
    //Mark UID as Mandatory
    var MandatoryCFs = ["UID", "Description"];
    $(document).ready(ExecuteOrDelayUntilScriptLoaded(MainFunction, "sp.js"));
    function MainFunction() {
        Mandatory();
    }
    function Mandatory(){
    $(".ms-accentText").each(function() {
    var text = $(this).text(); 
    $(this).text(text.append(MandatoryCFs, ' *'));
    });
    }    
    </script>

Replace multiple strings by using list of |Regex

    //Mark UID as Mandatory
    var MandatoryCFs = ["UID", "Description"];
    $(document).ready(ExecuteOrDelayUntilScriptLoaded(MainFunction, "sp.js"));
    function MainFunction() {
        Mandatory();
    }
    function Mandatory(){
      $(".ms-accentText").each(function() {
        var text = $(this).text(); 
        $(this).text(text.replace(new RegExp(MandatoryCFs.join('|'),'g'), '$& *'));
      });
    }

or like this if you don't need to the replaced strings to be dynamic:

text.replace(/UID|Description/g, '$& *')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM