[Regular Expressions] Introduction

时间:2023-03-09 00:03:45
[Regular Expressions] Introduction
var str = "Is this This?";

//var regex = new RegExp("is", "gi");
var regex = /is/gi; //console.log(regex.test(str));
console.log(regex.exec(str)); //["Is", index: 0, input: "Is this This?"]
console.log(regex.exec(str)); //["is", index: 5, input: "Is this This?"]
console.log(regex.exec(str)); //["is", index: 10, input: "Is this This?"]
console.log(regex.exec(str)); //null console.log(str.match(regex)); //["Is", "is", "is"] console.log(str.replace(regex, "XX")); //"XX thXX ThXX?" console.log(str.search(regex)); // 0, return the first index that found

-----------------------------

App:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Javascript Regular Expressions: Introduction</title>
<style>
pre {
line-height: 2;
} span {
background-color: #eee;
padding: 1px;
outline: 1px solid #999;
} </style>
</head>
<body>
<pre></pre>
</body>
</html>
'use strict';

const output = (str, regex, target) => {
target.innerHTML =
str.replace(regex, str => `<span>${str}</span>`);
} var str = `Is this This?`; //var regex = new RegExp("is", "g");
var regex = /is/gi; output(str, regex, document.querySelector('pre')) // console.log(regex.test(str));
// console.log(regex.exec(str));
// console.log(regex.exec(str));
// console.log(regex.exec(str));
// console.log(regex.exec(str));
// console.log(str.match(regex));
// console.log(str.replace(regex, str => "XX"));
// console.log(str.search(regex));

[Regular Expressions] Introduction