WEB_TECH/javascript

String객체

지식사랑 2012. 9. 13. 12:41

String은 문자열 객체 입니다.

자바스크립트에서 어찌보면 가장 중요하다고 할 수 있는 객체입니다.

자주 사용되는 몇개의 메서드와 속성들은 잘 익혀두어야 합니다.


length속성은 String의 문자열의 길이를 표시해 주는 속성입니다.


다음을 실행해 보겠습니다.


<script type="text/javascript">

var txt = "Hello World!";

document.write(txt.length);

</script>


이렇게 하면 12가 출력됩니다.




자바스크립트 메서드로 스타일을 사용해 봅시다.

이것은 스타일시트처럼 정교하진 않습니다. 


다음은 볼드나 소문자 대문자 이탤릭등 기본적인 스타일을 사용하는 예제입니다.


<script type="text/javascript">


var txt = "Hello World!";


document.write("<p>Big: " + txt.big() + "</p>");

document.write("<p>Small: " + txt.small() + "</p>");


document.write("<p>Bold: " + txt.bold() + "</p>");

document.write("<p>Italic: " + txt.italics() + "</p>");


document.write("<p>Fixed: " + txt.fixed() + "</p>");

document.write("<p>Strike: " + txt.strike() + "</p>");


document.write("<p>Fontcolor: " + txt.fontcolor("green") + "</p>");

document.write("<p>Fontsize: " + txt.fontsize(6) + "</p>");


document.write("<p>Subscript: " + txt.sub() + "</p>");

document.write("<p>Superscript: " + txt.sup() + "</p>");


document.write("<p>Link: " + txt.link("http://www.w3schools.com") + "</p>");


document.write("<p>Blink: " + txt.blink() + " (does not work in IE, Chrome, or Safari)</p>");


</script>


아래와 같은 결과가 나옵니다.



indexOf("해당문자열") 는 해당문자열이 나오는 인덱스를 반환해 주는 메서드입니다.

아래의 예제를 실행시켜 보면 21이 나옵니다.


<!DOCTYPE html>

<html>

<body>


<p id="demo">버튼클릭 </p>

<button onClick="myFunction()"> 실행 </button>

<script type="text/javascript">

function myFunction(){

var str="Hello world, welcome to the universe.";

var n = str.indexOf("to");

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

}

</script>


</body>

</html>




match("해당문자열") 메서드는 문자열에서 해당문자열이 있는지 확인해서 있으면 해당문자열을 출력해 주고 없으면 null을 반환하는 메서드입니다.

다음 예제를 실행해 봅시다.

<!DOCTYPE html>

<html>

<body>

<script type="text/javascript">

var str="Hello world!";

document.write(str.match("world") + "<br />");  //world

document.write(str.match("World") + "<br />");  // null

document.write(str.match("worlld") + "<br />");  // null

document.write(str.match("world!"));                 //world!

</script>

</body>

</html>



replace("특정문자열", "교체문자열") 함수는 특정문자열을 교체문자열로 바꿔주는 메서드입니다.
<!DOCTYPE html>
<html>
<body>

<p>Click the button to replace "Microsoft" with "W3Schools" in the paragraph below:</p>
<p id = "demo">Visit Microsoft!</p>
<button onclick = "myFunction()">Try it</button>

<script type="text/javascript">
function myFunction(){
var str = document.getElementById("demo").innerHTML;
var n = str.replace("Microsoft","이재웅홈");
document.getElementById("demo").innerHTML = n;
}
</script>

</body>
</html>