게시판의 글 내용을 <textarea>태그로 작성 중 줄 바꿈이 적용되지 않아 replace() 메소드를 활용하기로 했다.
w3schools.com 에 따르면....
JavaScript String replace() Method
Definition and Usage
The replace() method searches a string for a specified value, or a regular expression, and returns a new string where the specified values are replaced.
Note: If you are replacing a value (and not a regular expression), only the first instance of the value will be replaced. To replace all occurrences of a specified value, use the global (g) modifier (see "More Examples" below).
Read more about regular expressions in our RegExp Tutorial and our RegExp Object Reference.
This method does not change the original string.
Syntax
string.replace(searchvalue, newvalue)
Parameter Values
Parameter | Description |
---|---|
searchvalue | Required. The value, or regular expression, that will be replaced by the new value |
newvalue | Required. The value to replace the search value with |
replace() 메소드는 문자열의 특정 값이나 정규식을 찾아 원하는 문자열로 변경해준다~라는 의미인 듯 하다.
노트에 따르면 변경하고자 하는 문자열의 첫번째 검색에 한하여 원하는 문자열로 변경해준다고 한다. 여기까지는 기존에 알던 사실.
그러나 추가적으로!! global (g) modifier를 사용하면 모든 검색에 대해 원하는 문자열로 변경해준다고 한다!!
코드에 적용해보았다.
<form role='writeForm' action='/write' method='post>
<textarea name='contents'></textarea> // <textarea>로 문자열을 입력받는다
<button type='submit'>등록</button>
</form>
<script>
$(document).ready(fucntion(e){
var writeForm = $("form[role='writeForm']");
$("button[type='submit']").on("click", fucntion(e){ // 등록 button 클릭시 이벤트 발생
e.preventDefault();
var orginalStr = $("textarea[name='contents']").val(); // 기존 <textarea>에 입력된 문자열
var newStr = originalStr.replace(/(\r\n|\n)/g, '<br/>'); // 줄바꿈을 <br/>태그로 변경한 새로운 문자열
$("textarea[name='contents']").val(newStr); // 수정된 문자열을 <textarea>에 입력
writeForm.submit(); // submit
});
});
</script>
부족한 부분은 피드백 부탁드립니다.
감사합니다.
인용자료 :
w3schools.com : https://www.w3schools.com/jsref/jsref_replace.asp
written by 미니아빠