2012-05-30 4 views
1

HTML 템플릿을 렌더링 할 때마다 여러 단어를 새 단어로 바꾸려고합니다.여러 단어를 새 단어로 바꾸는 자바 스크립트 정규식

세 개의 다른 단어를 찾기 위해 세 번 반복하여 템플릿을 반복해야하는 대신 은 세 단어와 그 대체 단어 인을 결합하여 한 번만 템플릿을 반복합니다. (또한 분명히 아래의 코드는 위의 다른 두 대체 시도보다 우선하기 때문에 마지막 단어 {id} 만 바꿉니다.

 $.get('/templates/list-item.html', function(data) { 
      var template = data, 
       tmp = ''; 

      $.getJSON('conf.json', function(data) { 
      var items = [], 
       list = data.default; 

      for (var item in list) { 
       var name = item.name, 
        value = list[item].value, 
        id = list[item].id; 

       tmp = template.replace('{name}', name); 
       tmp = template.replace('{value}', value); 
       tmp = template.replace('{id}', id); 

       items.push(tmp); 
      } 

      $('<div/>', { 
       html: items.join('') 
      }).appendTo('body'); 
      }); 
     }); 

분명히 렌더링 템플릿 JS와 함께 할 수 없습니다해야하지만, 그것은 단지 내부 용이기 때문에, 어떤 백엔드를 사용할 수없는 그것은 구글에 의해 색인 할 필요가 없습니다, 그것은 당분간 괜찮아요.

답변

9

콜백 함수를 사용하여 템플릿 변수를 바꿀 수 있습니다. 예를 들어 고려 :

template = "{foo} and {bar}" 
data = {foo:123, bar:456} 

template.replace(/{(\w+)}/g, function($0, $1) { 
    return data[$1]; 
}); 

는 또한 map()와 루프를 교체하는 게 좋을 것 :

items = $.map(list, function(item) { 
    var data = {name: item.name, value:.... etc } 
    return template.replace(/{(\w+)}/g, function($0, $1) { 
     return data[$1]; 
    }); 
} 

/{(\w+)}/g

은 기본적으로 다음과 같은 의미 :

/    - start pattern 
{    - match { literally 
    (   - begin group 1 
     \w  - a "word" character (letter+digit+underscore) 
     +  - repeat once or more 
    )   - end group 1 
}    - match } literally 
/    - end pattern 
g    - match globally, i.e. all occurences 

콜백 기능은,라고 할 때 전체 일치를 첫 번째 매개 변수로 가져 오며 그룹 1의 값을 두 번째 매개 변수로 가져옵니다. 따라서 {foobar}이 표시되면 callback("{foobar}", "foobar")이 호출됩니다.

+0

환상적! – patad

+0

$ .map()을 사용할 때의 이점은 무엇입니까? 루프를 사용하는 것보다 빠르거나 읽기가 더 쉬울까요? – patad

+0

'/{(\ w +)} /'는 [정규 표현식]이다. (http://www.javascriptkit.com/javatutors/re.shtml)'map'은 읽기 쉽고 [루프 클로저 (http : /stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) 문제 – georg