본문 바로가기

IT칼럼/JavaScript

Regular Expression


What Is a Regular Expression?

A regular expression is a sequence of characters that forms a search pattern.

When you search for data in a text, you can use this search pattern to describe what you are searching for.

A regular expression can be a single character, or a more complicated pattern.

Regular expressions can be used to perform all types of text search and text replace operations.

Syntax

/pattern/modifiers;

Example

var patt = /world/i;

Example explained:

/world/i  is a regular expression.

world is a pattern (to be used in a search).

i  is a modifier (modifies the search to be case-insensitive).



Regular Expression을 사용한 문자열 replace() 예제


Example

Use a case insensitive regular expression to replace Microsoft with W3Schools in a string:

var str = "Visit Microsoft!";
var res = str.replace(/microsoft/i, "Apple");

The result in res will be:

Visit Apple!


<!DOCTYPE html>

<html>

<body>


<h2>JavaScript Regular Expressions</h2>

<p>Replace "microsoft" with "Apple" in the paragraph below:</p>

<button onclick="myFunction()">Try it</button>

<p id="demo">Please visit Microsoft and Microsoft !</p>


<script>

function myFunction() {

  var str = document.getElementById("demo").innerHTML; 

  var txt = str.replace(/microsoft/i,"Apple");

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

}

</script>


</body>

</html> 




참고자료 : https://www.w3schools.com/js/js_regexp.asp



'IT칼럼 > JavaScript' 카테고리의 다른 글

ExpressJS 를 이용하여 index.html 파일 view  (0) 2019.04.30
JSX의 개념과 기본 문법 소개  (0) 2019.04.16