문자열이 JS의 regex와 일치하는지 확인합니다.
자바스크립트(jQuery와 함께 사용할 수 있음)를 사용하여 클라이언트 측 검증을 수행하여 문자열이 regex와 일치하는지 확인합니다.
^([a-z0-9]{5,})$
이상적으로는 true 또는 false를 반환하는 표현입니다.
저는 JavaScript 초보자입니다.match()
내가 필요한 걸 해?문자열의 일부가 전체가 아니라 정규식과 일치하는지 확인하는 것 같습니다.
원하는 것이 부울 결과인 경우 사용합니다.
console.log(/^([a-z0-9]{5,})$/.test('abc1')); // false
console.log(/^([a-z0-9]{5,})$/.test('abc12')); // true
console.log(/^([a-z0-9]{5,})$/.test('abc123')); // true
...그리고 당신은 그것을 제거할 수 있습니다.()
캡처가 필요없기 때문에 regexp에서 추출할 수 있습니다.
사용하다test()
방법:
var term = "sample1";
var re = new RegExp("^([a-z0-9]{5,})$");
if (re.test(term)) {
console.log("Valid");
} else {
console.log("Invalid");
}
사용할 수 있습니다.match()
또, 다음과 같이 합니다.
if (str.match(/^([a-z0-9]{5,})$/)) {
alert("match!");
}
그렇지만test()
여기 보시는 것처럼 더 빠른 것 같습니다.
의 중요한 차이점match()
그리고.test()
:
match()
문자열로만 동작합니다만 동작합니다.test()
는 정수에서도 사용할 수 있습니다.
12345.match(/^([a-z0-9]{5,})$/); // ERROR
/^([a-z0-9]{5,})$/.test(12345); // true
/^([a-z0-9]{5,})$/.test(null); // false
// Better watch out for undefined values
/^([a-z0-9]{5,})$/.test(undefined); // true
사용하다/youregexp/.test(yourString)
문자열이 regexp와 일치하는지 여부만 확인하는 경우.
let str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
let regexp = /[a-d]/gi;
console.log(str.match(regexp));
다음은 특정 HTML 태그를 찾는 예입니다./someregex/.test()
부울을 반환합니다.
if(/(span|h[0-6]|li|a)/i.test("h3")) alert('true');
잊지 말고 표시해 주세요.^
스트링의 선두와$
스트링 전체의 정확한 일치를 테스트하는 경우.
예제:
/[a-z]+/.test('aaa111'); // true
/^[a-z]+$/.test('aaa111'); // false
const regExpStr = "^([a-z0-9]{5,})$"
const result = new RegExp(regExpStr, 'g').test("Your string") // here I have used 'g' which means global search
console.log(result) // true if it matched, false if it doesn't
해라
/^[a-z\d]{5,}$/.test(str)
console.log( /^[a-z\d]{5,}$/.test("abc123") );
console.log( /^[a-z\d]{5,}$/.test("ab12") );
일치하는 항목이 없으면 null을 반환하는 실행 메서드를 사용하는 것이 좋습니다.그렇지 않으면 도움이 되는 오브젝트가 반환됩니다.
let case1 = /^([a-z0-9]{5,})$/.exec("abc1");
console.log(case1); //null
let case2 = /^([a-z0-9]{5,})$/.exec("pass3434");
console.log(case2); // ['pass3434', 'pass3434', index:0, input:'pass3434', groups: undefined]
이거 한 번 해봐, 나한테는 괜찮아.
<input type="text" onchange="CheckValidAmount(this.value)" name="amount" required>
<script type="text/javascript">
function CheckValidAmount(amount) {
var a = /^(?:\d{1,3}(?:,\d{3})*|\d+)(?:\.\d+)?$/;
if(amount.match(a)){
alert("matches");
}else{
alert("does not match");
}
}
</script>
이 꽃을 시험해 보세요.
/^[a-z0-9\_\.\-]{2,20}\@[a-z0-9\_\-]{2,20}\.[a-z]{2,9}$/.test('abc@abc.abc');
진실의
regex에 ^ 및 $를 사용하지 않으려면 다음과 같은 작업을 수행할 수 있습니다.
let reg = /[a-zA-Z0-9]+/g
let txt = "hello"
let matches = reg.exec(txt)[0] == txt
console.log(`It ${matches ? "does" : "doesn't"} match`)
업데이트/추가
쿼리 문자열이 URL에 없는 경우 다음 솔루션은 URL에 매개 변수를 추가하는 작업을 수행합니다. 매개 변수가 이미 있는 경우 매개 변수가 업데이트됩니다.
function updateUrlParameter(url, param, value) {
var regex = new RegExp("(?<=[?|&])(" + param + "=)[^&]+", "i");
if (regex.test(url)) {
return url.replace(regex, param + "=" + value);
} else {
if (window.location.search) {
return `${url}&${param}=${value}`;
}else{
return `${url}?${param}=${value}`;
}
}
}
언급URL : https://stackoverflow.com/questions/6603015/check-whether-a-string-matches-a-regex-in-js
'itsource' 카테고리의 다른 글
PHP를 사용하여 IP 주소 국가 가져오기 (0) | 2022.09.13 |
---|---|
JPA: 대규모 결과 세트에 대해 반복하기 위한 적절한 패턴은 무엇입니까? (0) | 2022.09.13 |
query Selector 및 query SelectorJavaScript의 모든 vs getElementsByClassName 및 getElementById (0) | 2022.09.13 |
MySQL CREATE/DROP USER가 0을 반환함 (0) | 2022.09.13 |
요소를 어레이에 특정 위치에 삽입하려면 어떻게 해야 합니까? (0) | 2022.09.13 |