- 영어와 띄어쓰기만 남기기

value.replace(/[^(a-z )]/gi, "");     //    g는 모든 /  / 정규식에 대하여,   i는 대소문자 구분 제외

 

- 3자리 마다 콤마 찍기 (금액 포맷)

value.replace(/\B(?=(\d{3})+(?!\d))/g,",");

 

- , 콤마 지우기

value.replace(/,/g, "");

 

- 숫자만 남기기

value.replace(/[^0-9]/g, "")

 

- 전화번호 포맷

value.replace(/(^02.{0}|^01.{1}|[0-9]{3})([0-9]+)([0-9]{4})/, '$1-$2-$3');

 

- 보너스

const input ="123";

input.charCodeAt(0); // "1" 에 대한 숫자 49 반환

input.charCodeAt(1); // "2" 에 대한 숫자 50 반환

 

String.fromCharCode(65)       A 반환

`${함수명}` 을 이용하여 함수 값을 가져올 수 있습니다.

아래는 html전용 예제 코드입니다.

 

function test () { return "test!"; } 가 출력됩니다.

<html>
  <body>
    <div id="show"></div>
    <script>

      function test () {
        return "test!";
      }

       const target = document.getElementById("show");
       target.innerHTML = `${test}`;
    </script>
  </body>
</html>

React 입문하면서 자바스크립트 공부 중 궁금한 사항이 생겨 결과를 정리 해봤습니다.

(테스트를 더 해보고 싶다면 아래 코드에 label, testValue 에 값을 추가해보시면 되겠습니다.)

 

&& 연산자 (0을 제외한 숫자와 문자들은 모두 true로 인식이 됩니다.)

수식 결과
null && 'T'
 
undefined && 'T'
 
'' && 'T'
 
' ' && 'T'
T
0 && 'T'
0
'0' && 'T'
T
1 && 'T'
T
-1 && 'T'
T
true && 'T'
T
"true" && 'T'
T
false && 'T'
 
"false" && 'T'
T

? 연산자 (3항 연산자)

수식 결과
null ? 'T' : 'F'
F
undefined ? 'T' : 'F'
F
'' ? 'T' : 'F'
F
' ' ? 'T' : 'F'
T
0 ? 'T' : 'F'
F
'0' ? 'T' : 'F'
T
1 ? 'T' : 'F'
T
-1 ? 'T' : 'F'
T
true ? 'T' : 'F'
T
"true" ? 'T' : 'F'
T
false ? 'T' : 'F'
F
"false" ? 'T' : 'F'
T

?? 연산자 ( null ?? 'F'   로 입력을 하였는데 내부적으로 아래와 같은 코드로 변경이 되네요.)

 null, undefined 인 경우에만 값을 넣어줄 수 있습니다.

수식 결과
null !== null && null !== void 0 ? null : 'F'      (null ?? 'F')
F
undefined !== null && undefined !== void 0 ? undefined : 'F'     (undefined ?? 'F')
F
'' !== null && '' !== void 0 ? '' : 'F'
 
' ' !== null && ' ' !== void 0 ? ' ' : 'F'
 
0 !== null && 0 !== void 0 ? 0 : 'F'
0
'0' !== null && '0' !== void 0 ? '0' : 'F'
0
1 !== null && 1 !== void 0 ? 1 : 'F'
1
-1 !== null && -1 !== void 0 ? -1 : 'F'
-1
true !== null && true !== void 0 ? true : 'F'
 
"true" !== null && "true" !== void 0 ? "true" : 'F'
true
false !== null && false !== void 0 ? false : 'F'
 
"false" !== null && "false" !== void 0 ? "false" : 'F'
false

|| 연산자 (null, undefined, blank, false, 0 인 경우에 기본 값 지정이 가능합니다.)

수식 결과
null || 'Or Default'
Or Default
undefined || 'Or Default'
Or Default
'' || 'Or Default'
Or Default
' ' || 'Or Default'
 
0 || 'Or Default'
Or Default
'0' || 'Or Default'
0
1 || 'Or Default'
1
-1 || 'Or Default'
-1
true || 'Or Default'
 
"true" || 'Or Default'
true
false || 'Or Default'
Or Default
"false" || 'Or Default'
false

 

아래는 로그에 찍히는 내용으로

xml 형태가 아닌 react에서 실제 변경되어 사용되는 모습이 흥미롭네요!

 

읽어 온 함수 내용 :  value => {
    return /*#__PURE__*/(0,react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxDEV)("div", {
      children: value && 'T'
    }, void 0, false, {
      fileName: _jsxFileName,
      lineNumber: 72,
      columnNumber: 12
    }, undefined);
  }

 

export const OperationExample = () => {
  const label = ['null', 'undefined', "''", "' '", '0', "'0'", '1', '-1', 'true', '"true"', 'false', '"false"'];
  const testValue = [null, undefined, '', ' ', 0, '0', 1, -1, true, "true", false, "false"];
  let keyPrefix = 0;

  //css 한 파일로 하려고 선언...
  const style = {
    border: '1px solid black',
    borderCollapse: 'collapse',
    textAlign: 'center',
  };

  const CustomTable = ({ condition }) => {
    keyPrefix++;

    return (
      <table key={keyPrefix} style={style}>
        <tbody>
          <tr style={style}>
            <td style={style}> 수식 </td>
            <td style={style}> 결과 </td>
          </tr>
          {testValue.map((v, index) => {
            const trKey = keyPrefix + 'tr' + index;
            const tdLabelkey = keyPrefix + 'label' + index;
            const tdValuekey = keyPrefix + 'value' + index;

            const content = GetFunctionCode(condition, index);

            return (
              <tr key={trKey} style={style}>
                <td key={tdLabelkey} style={style}>
                  {content}
                </td>
                <td key={tdValuekey} style={style}>
                  {condition(v)}
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
    );
  };

  //`${함수명}` 을 통해 함수 코드를 볼 수 있습니다!
  const GetFunctionCode = (fn, index) => {
    const functionToString = `${fn}`; //재미있는 부분..! 함수 내용을 읽어옵니다.
    const target = 'children: '; //읽어온 함수에서 children 항목을 찾습니다.
    let result = '';
    let i = functionToString.indexOf(target) + target.length;

    console.log('읽어 온 함수 내용 : ', functionToString);

    //children에 담긴 코드 부분만 추출해줍니다.
    for (i; i < functionToString.length; ++i) {
      if (functionToString[i] === '}') {
        break;
      }
      result += functionToString[i];
    }

    return result.replaceAll('value', label[index]).trim(); //함수 핵심 로직만 읽어오기
  };

  const AndCondition = (value) => {
    return <div>{value && 'T'}</div>;
  };

  const SingleQuestionMarkCondition = (value) => {
    return <div>{value ? 'T' : 'F'}</div>;
  };

  const DoubleQuestionMarkCondition = (value) => {
    return <div>{value ?? 'F'}</div>;
  };

  const OrCondition = (value) => {
    return <div>{value || 'Or Default'}</div>;
  };

  return (
    <div>
      <b>&& 연산자</b>
      <CustomTable condition={AndCondition} />
      <b>? 연산자</b>
      <CustomTable condition={SingleQuestionMarkCondition} />
      <b>?? 연산자</b>
      <CustomTable condition={DoubleQuestionMarkCondition} />
      <b>|| 연산자</b>
      <CustomTable condition={OrCondition} />
    </div>
  );
};

Object.prototype.toString.call (  target  )

  해당 오브젝트의 타입을 알려줍니다.

const a = 123;
const b = "test";
const c = [1, 2, 3];
const d = () => { alert("is function!"); }

const aType = Object.prototype.toString.call(a); //[object Number]
const bType = Object.prototype.toString.call(b); //[object String]
const cType = Object.prototype.toString.call(c); //[object Array]
const dType = Object.prototype.toString.call(d); //[object Function]

//응용버전 - 타입 판별 방법.
const isFunction = /Function/.test(dType); //1. 정규식으로 판별
const isFunction2 = dType.indexOf("Function"); //2. indexOf 로 contain 판별

alert(
  "aType : " + aType + "\n" +
  "bType : " + bType + "\n" +
  "cType : " + cType + "\n" +
  "dType : " + dType + "\n" +
  "isFunction : " + isFunction + "\n" +
  "isFunction2 : " + isFunction2
);

/* 결과
aType : [object Number]
bType : [object String]
cType : [object Array]
dType : [object Function]
isFunction : true
isFunction2 : 8
*/

 

+ Recent posts