JavaScript replace/regex

后端 未结 3 527
囚心锁ツ
囚心锁ツ 2020-11-27 14:02

Given this function:

function Repeater(template) {

    var repeater = {

        markup: template,

        replace: function(pattern, value) {
                     


        
3条回答
  •  情书的邮戳
    2020-11-27 14:32

    Your regex pattern should have the g modifier:

    var pattern = /[somepattern]+/g;
    

    notice the g at the end. it tells the replacer to do a global replace.

    Also you dont need to use the RegExp object you can construct your pattern as above. Example pattern:

    var pattern = /[0-9a-zA-Z]+/g;
    

    a pattern is always surrounded by / on either side - with modifiers after the final /, the g modifier being the global.

    EDIT: Why does it matter if pattern is a variable? In your case it would function like this (notice that pattern is still a variable):

    var pattern = /[0-9a-zA-Z]+/g;
    repeater.replace(pattern, "1234abc");
    

    But you would need to change your replace function to this:

    this.markup = this.markup.replace(pattern, value);
    

提交回复
热议问题