programing

새 라인 / 캐리지 리턴을 element.textContent에 삽입하려면 어떻게해야합니까?

goodcopy 2021. 1. 17. 11:55
반응형

새 라인 / 캐리지 리턴을 element.textContent에 삽입하려면 어떻게해야합니까?


어리석게 들릴지 모르지만 여전히 적절한 답을 찾지 못했습니다.

새 DOM 요소를 동적으로 만들고 textContent / innerText를 JS 문자열 리터럴로 채우고 싶다고 가정 해 보겠습니다.
문자열이 너무 길어서 세 부분으로 나누고 싶습니다.

var h1 = document.createElement("h1");

h1.textContent = "This is a very long string and I would like to insert a carriage return HERE...
moreover, I would like to insert another carriage return HERE... 
so this text will display in a new line";

문제는 내가 쓰면

h1.textContent = "...I would like to insert a carriage return here... \n";

브라우저가 '\ n'을 순수한 텍스트로 간주하고 그대로 표시하기 때문에 작동하지 않습니다 (\ r도 작동하지 않음).

반면에 textContent 대신 h1.innerHTML을 변경하고 다음과 같이 작성할 수 있습니다.

h1.innerHTML = "...I would like to insert a carriage return here...<br />";

여기에서는 <br />이 작업을 수행하지만 그렇게하면 텍스트 콘텐츠뿐만 아니라 h1의 모든 HTML 콘텐츠가 대체됩니다.

내 문제를 해결하는 간단한 방법이 있습니까?
다른 줄에 텍스트를 표시하기 위해 여러 블록 요소를 만드는 데 의지하지 않습니다.
어떤 아이디어라도 대단히 감사하겠습니다.
미리 감사드립니다.


이 질문이 오래전에 게시 된 것을 알고 있습니다.

며칠 전에 비슷한 문제가 발생하여 웹 서비스의 값을 json형식으로 전달 하고 table cell contentText.

예를 들어 값이 형식으로 전달되기 "text row1\r\ntext row2"때문입니다.

새로운 줄 textContent을 사용하려면 \r\n마지막으로 css를 사용해야했고 white-space: pre-line;(텍스트는 필요할 때 줄 바꿈하고 줄 바꿈) 모든 것이 잘됩니다.

또는을 사용할 수 있으며 white-space: pre;텍스트는 줄 바꿈에서만 줄 바꿈됩니다 (이 경우 \r\n).

따라서 줄 바꿈에서만 텍스트를 줄 바꿈하여 해결하는 방법에 대한 예제가 있습니다.

var h1 = document.createElement("h1");

//setting this css style solving problem with new line in textContent
h1.setAttribute('style', 'white-space: pre;');

//add \r\n in text everywhere You want for line-break (new line)
h1.textContent = "This is a very long string and I would like to insert a carriage return \r\n...";
h1.textContent += "moreover, I would like to insert another carriage return \r\n...";
h1.textContent += "so this text will display in a new line";

document.body.appendChild(h1);


나는 얼마 전에 이것을 만났다. 캐리지 리턴 (CODE 13)의 ASCII 표현을 사용하는 것이 좋은 해결책이라는 것을 알았습니다. JavaScript에는 String.fromCharCode()ASCII 코드의 문자열 버전 또는 쉼표로 구분 된 여러 코드를 생성 하는 편리한 기능이 있습니다. 제 경우에는 긴 문자열에서 CSV 파일을 생성하여 텍스트 영역에 써야했습니다. 텍스트 영역에서 텍스트를 잘라내어 메모장에 저장할 수 있어야했습니다. <br />메서드 를 사용하려고 하면 캐리지 리턴이 유지되지 않지만 fromCharCode 메서드를 사용하면 리턴이 유지됩니다. 아래 내 코드를 참조하십시오.

h1.innerHTML += "...I would like to insert a carriage return here..." + String.fromCharCode(13);
h1.innerHTML += "Ant the other line here..." + String.fromCharCode(13);
h1.innerHTML += "And so on..." + String.fromCharCode(13);
h1.innerHTML += "This prints hello: " + String.fromCharCode(72,69,76,76,79);

이 메서드에 대한 자세한 내용은 여기를 참조하십시오. w3Schools-fromCharCode ()

ASCII 코드는 여기를 참조하십시오 : ASCII 코드


정규식을 사용하여 '\ n'또는 '\ n \ r'문자를 '<br />'로 바꿀 수 있습니다.

당신은 이것을 가지고 있습니다 :

var h1 = document.createElement("h1");

h1.textContent = "This is a very long string and I would like to insert a carriage return HERE...
moreover, I would like to insert another carriage return HERE... 
so this text will display in a new line";

다음과 같이 문자를 바꿀 수 있습니다.

h1.innerHTML = h1.innerHTML.replace(/\n\r?/g, '<br />');

String 및 Regex 객체에 대한 javascript 참조를 확인하십시오.

http://www.w3schools.com/jsref/jsref_replace.asp

http://www.w3schools.com/jsref/jsref_obj_regexp.asp


문자열을 연결할 수 있습니다 ...

h1.innerHTML += "...I would like to insert a carriage return here...<br />";
h1.innerHTML += "Ant the other line here... <br />";
h1.innerHTML += "And so on...<br />";

jsFiddle.


사용 element.innerHTML="some \\\\n some";.


위의 솔루션 중 어느 것도 나를 위해 일하지 않았습니다. <p>요소에 줄 바꿈과 추가 텍스트를 추가하려고했습니다 . 일반적으로 Firefox를 사용하지만 브라우저 호환성이 필요합니다. Firefox 만 textContent속성을 지원하고 Internet Explorer 만 innerText속성을 지원하지만 둘 다 속성을 지원한다는 것을 읽었습니다 innerHTML. 그러나 이러한 속성을 추가 <br />하거나 추가 하지 \n않으면 \r\n새 줄이 생성 되지 않았습니다 . 그러나 다음은 작동했습니다.

<html>
<body>
<script type="text/javascript">
  function modifyParagraph() {

  var p;
  p=document.getElementById("paragraphID");
  p.appendChild(document.createElement("br"));
  p.appendChild(document.createTextNode("Additional text."));
}    
</script>

<p id="paragraphID">Original text.</p>

<input type="button" id="pbutton" value="Modify Paragraph" onClick="modifyParagraph()" />
</body>
</html>

삽입이 \\n작동 한다는 것을 알았습니다 . 즉, 이스케이프 된 개행 문자를 이스케이프합니다.


다음 코드는 잘 작동합니다 (FireFox, IE 및 Chrome에서).

var display_out = "This is line 1" + "<br>" + "This is line 2";

document.getElementById("demo").innerHTML = display_out;

nelek의 답변은 지금까지 게시 된 가장 좋은 답변이지만 CSS 값 : white-space : pre를 설정하는 데 의존하며 이는 바람직하지 않을 수 있습니다.

I'd like to offer a different solution, which tries to tackle the real question that should've been asked here:

"How to insert untrusted text into a DOM element?"

If you trust the text, why not just use innerHTML?

domElement.innerHTML = trustedText.replace(/\r/g, '').replace(/\n/g, '<br>');

should be sufficient for all the reasonable cases.

If you decided you should use .textContent instead of .innerHTML, it means you don't trust the text that you're about to insert, right? This is a reasonable concern.

For example, you have a form where the user can create a post, and after posting it, the post text is stored in your database, and later on appended to pages whenever other users visit the relevant page.

If you use innerHTML here, you get a security breach. i.e., a user can post something like

[script]alert(1);[/script]

(try to imagine that [] are <>, apparently stack overflow is appending text in unsafe ways!)

which won't trigger an alert if you use innerHTML, but it should give you an idea why using innerHTML can have issues. a smarter user would post

[img src="invalid_src" onerror="alert(1)"]

which would trigger an alert for every other user that visits the page. Now we have a problem. An even smarter user would put display: none on that img style, and make it post the current user's cookies to a cross domain site. Congratulations, all your user login details are now exposed on the internet.

So, the important thing to understand is, using innerHTML isn't wrong, it's perfect if you're just using it to build templates using only your own trusted developer code. The real question should've been "how do I append untrusted user text that has newlines to my HTML document".

This raises a question: which strategy do we use for newlines? do we use [br] elements? [p]s or [div]s?

Here is a short function that solves the problem:

function insertUntrustedText(domElement, untrustedText, newlineStrategy) {
    domElement.innerHTML = '';
    var lines = untrustedText.replace(/\r/g, '').split('\n');
    var linesLength = lines.length;
    if(newlineStrategy === 'br') {
        for(var i = 0; i < linesLength; i++) {
            domElement.appendChild(document.createTextNode(lines[i]));
            domElement.appendChild(document.createElement('br'));
        }
    }
    else {
        for(var i = 0; i < linesLength; i++) {
            var lineElement = document.createElement(newlineStrategy);
            lineElement.textContent = lines[i];
            domElement.appendChild(lineElement);
        }
    }
}

You can basically throw this somewhere in your common_functions.js file and then just fire and forget whenever you need to append any user/api/etc -> untrusted text (i.e. not-written-by-your-own-developer-team) to your html pages.

usage example:

insertUntrustedText(document.querySelector('.myTextParent'), 'line1\nline2\r\nline3', 'br');

the parameter newlineStrategy accepts only valid dom element tags, so if you want [br] newlines, pass 'br', if you want each line in a [p] element, pass 'p', etc.

ReferenceURL : https://stackoverflow.com/questions/9980416/how-can-i-insert-new-line-carriage-returns-into-an-element-textcontent

반응형