2013-03-27 6 views
1

내가 가진 가정하면 다음과 같은 : 나는 그런 내가 문자열의 같은 출력이 처리 할 수 ​​있도록 수있는 몇 가지 기능이나 방법이 있나요js에서 텍스트를 바꾸는 방법은 무엇입니까?

var array = [ 
"is <b>a test</b>", 
"of the <div style=\"color:red\">battle</div> system" 
] 

:

var s = "This is a test of the battle system." 

나는 배열했다

var p = "This is <b>a test</b> of the <div style=\"color:red\">battle</div> system." 

배열의 임의 요소를 기반으로할까요?

배열 요소는 순서대로 실행되어야합니다. 배열 1의 첫 번째 요소를 살펴보면 문자열 "s"에서 "replace"할 올바른 위치를 찾습니다. 그런 다음 배열 요소 2를보고 문자열 "s"에서 "replace"할 올바른 위치를 찾으십시오. 난 당신이 내가 원래 생각했던 것보다 뭔가 다른 일을 할 생각 콜린 DeClue의 발언 후 : 문자열이 (비록> 어떤 <)

+1

나는 이러한 오류는 잘못된 구문 강조 주어진 즉시 분명하게하지 않는 궁금해 : 한 성가신 일이 자바 스크립트에는 escape 미리 정의 된 기능이 없기 때문에 정확한 문자열을 검색 사소한되지 않는 것입니다. 비록 내가 코드를 이해하지 못한다 할지라도 나는 여전히 뭔가 잘못되었다고 말할 수 있습니다. – elclanrs

답변

6

업데이트를 대시와 같은 숫자, 괄호, 그리고 다른 문자를 포함 할 수

참고. 여기

//your array 
var array = [ 
    "is <b>a test</b>", 
    "of the <div style=\"color:red\">battle</div> system" 
]; 
//create a sample span element, this is to use the built in ability to get texts for tags 
var cElem = document.createElement("span"); 

//create a clean version of the array, without the HTML, map might need to be shimmed for older browsers with a for loop; 
var cleanArray = array.map(function(elem){ 
    cElem.innerHTML = elem; 
    return cElem.textContent; 
}); 
//the string you want to replace on 
var s = "This is a test of the battle system." 

//for each element in the array, look for elements that are the same as in the clean array, and replace them with the HTML versions 
for(var i=0;i<array.length;i++){ 
    var idx;//an index to start from, to avoid infinite loops, see discussion with 6502 for more information 
    while((idx = s.indexOf(cleanArray[i],idx)) > -1){ 
    s = s.replace(cleanArray[i],array[i]); 
    idx +=(array[i].length - cleanArray[i].length) +1;//update the index 
    } 
} 
//write result 
document.write(s); 

그 작업을 예를 달성 할 수있는 방법입니다 http://jsbin.com/opudah/9/edit


원래 대답은, 경우에 이것은 당신이 모두 예

후 의미하는 것입니다. join

var s = array.join(" "); 

Here is a working example in codepen

+1

포스터가 원하는 것 같지 않습니다. 나는 포스터가's'로 시작하기를 원한다고 생각합니다. 마지막으로's'를 출력하기 위해 그것을 처리하는 데'array'를 사용합니다. –

+0

콜린 말이 맞습니다. 이건 제가 찾고있는 것이 아닙니다. "배열"의 모든 요소를 ​​가져 와서 문자열에 적용하여 원하는 결과 문자열을 얻으려고합니다. – Rolando

+0

@ColinDeClue 미안하지만, 내 잘못 이었어. 최근 편집보기 –

0

사용하여 당신이 original --> replacement쌍 배열을했습니다 가정합니다. HTML에서 텍스트를 추출하려면 실제로 작동하는 DOM 노드를 만든 다음 텍스트 콘텐츠를 추출해야합니다.

일단 텍스트가 있으면 replace 메서드를 정규식과 함께 사용할 수 있습니다.

function textOf(html) { 
    var n = document.createElement("div"); 
    n.innerHTML = html; 
    return n.textContent; 
} 

var subs = ["is <b>a test</b>", 
      "of the <div style=\"color:red\">battle</div> system"]; 

var s = "This is a test of the battle system" 

for (var i=0; i<subs.length; i++) { 
    var target = textOf(subs[i]); 
    var replacement = subs[i]; 
    var re = new RegExp(target.replace(/[\\[\]{}()+*$^|]/g, "\\$&"), "g"); 
    s = s.replace(re, replacement); 
} 

alert(s); 
관련 문제