Skip to content
-
JavaScript RegExp Reference
Last Updated :
05 Dec, 2024
RegExp stands for Regular Expression. A regular expression is a sequence of characters that forms a search pattern. The search pattern can be used for text search and text to replace operations. A regular expression can be a single character or a more complicated pattern.
Syntax:
new RegExp("(Regular Expressioncharactersnonword)")
Example: This example searches the words whose starting character is “A” and ending character is “C” with only one character in between them.
JavaScript
let str = "ABC, A3C, A C, AXXCC!";
let regex = /A.C/g;
console.log(str.match(regex));
Output[ 'ABC', 'A3C', 'A C' ]
The complete list of JavaScript RegExp is listed below:
JavaScript RegExp Constructor:
In JavaScript, a constructor gets called when an object is created using the new keyword.
RegExp(): It creates a new RegExp object.
JavaScript
const str = "geeksforgeeks"
const reg = new RegExp(/[g]/, 'g');
console.log(str.match(reg));
JavaScript RegExp Properties: A JavaScript property is a member of an object that associates a key with a value.
- Instance Property: An instance property is a property that has a new copy for every new instance of the class.
Instance Properties | Description |
---|
constructor | Return the RegExp constructor function for the object. |
dotAll | It checks if the 's' flag is used or not in the Regular Expression |
flags | This property returns the flag being used in the current RegExp object |
global | It specifies whether the 'g' flag is used or not |
hasIndices | It specifies whether the 'd' flag is used or not |
ignoreCase | It specifies whether the 'i' flag is used or not |
multiline | It specifies whether 'm' flag is set or not |
source | It returns the text of the RegExp object |
sticky | It specifies whether 'y' flag is used or not |
unicode | It specifies whether 'u' flag is used or not |
lastIndex | It specifies at which index to start the next match |
JavaScript RegExp Methods: JavaScript methods are the actions that can be performed on objects.
Instance Method:
If the method is called on an instance of a RegExp then it is called an instance method.
Instance Methods | Description |
---|
exec | It is used to test if the strings match |
test | It also checks if the string matches but the return type is different |
toString | It returns the string value of the Regular Expression |
The Different Metacharacters and Flags of RegExp is given below:
RegExp | Description |
---|
Metacharacter | Search single characters, except line terminator or newline. |
m | Perform multiline matching. |
\r | The RegExp \r Metacharacter carriage return characters. |
[abc] | Search for any character which is between the brackets. |
(x|y) | Search any of the specified characters (separated by |). |
\xxx | Find the character specified by an octal number xxx. |
\W | Find the non word character i.e. characters which are not from a to z, A to Z, 0 to 9. |
[^abc] | Search for any character which is not between the brackets. |
g | Find all the occurrences of the pattern instead of stopping after the first match i.e it performs a global match. |
[0-9] | Search any digit which is between the brackets. |
\s | Find the whitespace characters. |
\b | Find a match at the beginning or end of a word |
i | Perform case-insensitive matching in the string. |
\n | The RegExp \n Metacharacter in JavaScript is used to find the newline character. |
[^0-9] | Search for any digit which is not between the brackets. |
\B | Find a match that is not present at the beginning or end of a word. |
\f | Find the form feed character (form feed is a page-breaking ASCII control character). |
\w | Find the word character i.e. characters from a to z, A to Z, 0 to 9. It is the same as [a-zA-Z_0-9]. |
\d | Search digit characters. It is the same as [0-9]. |
\t | If it is found it returns the position else it returns -1. |
\D | Search non-digit characters i.e all the characters except digits. It is the same as [^0-9]. |
\0 | Find the NULL character. If it is found it returns the position else it returns -1. |
\v | Find the vertical tab character. If it is found it returns the position else it returns -1. |
* | Find the match of any string that contains zero or more occurrences of m. |
{X,} | Find the match of any string that contains a sequence of m, at least X times, where X is a number. |
?! | Find the match of any string which is not followed by a specific string m. |
{X} | Find the match of any string that contains a sequence of m, X times where X is a number. |
^ | Find the match of any string which contains m at the beginning of it. |
? | Find the match of any string that contains zero or one occurrence of m. |
$ | Find the match of any string which contains m at the end of it. |
+ | Find the match of any string that contains at least one m. |
\uxxxx | Find the Unicode character specified by a hexadecimal number XXXX. |
{X,Y} | Find the match of any string that contains a sequence of m, X to Y times where X, Y must be numbered. |
`;
$(commentSectionTemplate).insertBefore(".article--recommended");
}
loadComments();
});
});
function loadComments() {
if ($("iframe[id*='discuss-iframe']").length top_of_element && top_of_screen articleRecommendedTop && top_of_screen articleRecommendedBottom)) {
if (!isfollowingApiCall) {
isfollowingApiCall = true;
setTimeout(function(){
if (loginData && loginData.isLoggedIn) {
if (loginData.userName !== $('#followAuthor').val()) {
is_following();
} else {
$('.profileCard-profile-picture').css('background-color', '#E7E7E7');
}
} else {
$('.follow-btn').removeClass('hideIt');
}
}, 3000);
}
}
});
}
$(".accordion-header").click(function() {
var arrowIcon = $(this).find('.bottom-arrow-icon');
arrowIcon.toggleClass('rotate180');
});
});
window.isReportArticle = false;
function report_article(){
if (!loginData || !loginData.isLoggedIn) {
const loginModalButton = $('.login-modal-btn')
if (loginModalButton.length) {
loginModalButton.click();
}
return;
}
if(!window.isReportArticle){
//to add loader
$('.report-loader').addClass('spinner');
jQuery('#report_modal_content').load(gfgSiteUrl+'wp-content/themes/iconic-one/report-modal.php', {
PRACTICE_API_URL: practiceAPIURL,
PRACTICE_URL:practiceURL
},function(responseTxt, statusTxt, xhr){
if(statusTxt == "error"){
alert("Error: " + xhr.status + ": " + xhr.statusText);
}
});
}else{
window.scrollTo({ top: 0, behavior: 'smooth' });
$("#report_modal_content").show();
}
}
function closeShareModal() {
const shareOption = document.querySelector('[data-gfg-action="share-article"]');
shareOption.classList.remove("hover_share_menu");
let shareModal = document.querySelector(".hover__share-modal-container");
shareModal && shareModal.remove();
}
function openShareModal() {
closeShareModal(); // Remove existing modal if any
let shareModal = document.querySelector(".three_dot_dropdown_share");
shareModal.appendChild(Object.assign(document.createElement("div"), { className: "hover__share-modal-container" }));
document.querySelector(".hover__share-modal-container").append(
Object.assign(document.createElement('div'), { className: "share__modal" }),
);
document.querySelector(".share__modal").append(Object.assign(document.createElement('h1'), { className: "share__modal-heading" }, { textContent: "Share to" }));
const socialOptions = ["LinkedIn", "WhatsApp","Twitter", "Copy Link"];
socialOptions.forEach((socialOption) => {
const socialContainer = Object.assign(document.createElement('div'), { className: "social__container" });
const icon = Object.assign(document.createElement("div"), { className: `share__icon share__${socialOption.split(" ").join("")}-icon` });
const socialText = Object.assign(document.createElement("span"), { className: "share__option-text" }, { textContent: `${socialOption}` });
const shareLink = (socialOption === "Copy Link") ?
Object.assign(document.createElement('div'), { role: "button", className: "link-container CopyLink" }) :
Object.assign(document.createElement('a'), { className: "link-container" });
if (socialOption === "LinkedIn") {
shareLink.setAttribute('href', `https://www.linkedin.com/sharing/share-offsite/?url=${window.location.href}`);
shareLink.setAttribute('target', '_blank');
}
if (socialOption === "WhatsApp") {
shareLink.setAttribute('href', `https://api.whatsapp.com/send?text=${window.location.href}`);
shareLink.setAttribute('target', "_blank");
}
if (socialOption === "Twitter") {
shareLink.setAttribute('href', `https://twitter.com/intent/tweet?url=${window.location.href}`);
shareLink.setAttribute('target', "_blank");
}
shareLink.append(icon, socialText);
socialContainer.append(shareLink);
document.querySelector(".share__modal").appendChild(socialContainer);
//adding copy url functionality
if(socialOption === "Copy Link") {
shareLink.addEventListener("click", function() {
var tempInput = document.createElement("input");
tempInput.value = window.location.href;
document.body.appendChild(tempInput);
tempInput.select();
tempInput.setSelectionRange(0, 99999); // For mobile devices
document.execCommand('copy');
document.body.removeChild(tempInput);
this.querySelector(".share__option-text").textContent = "Copied"
})
}
});
// document.querySelector(".hover__share-modal-container").addEventListener("mouseover", () => document.querySelector('[data-gfg-action="share-article"]').classList.add("hover_share_menu"));
}
function toggleLikeElementVisibility(selector, show) {
document.querySelector(`.${selector}`).style.display = show ? "block" : "none";
}
function closeKebabMenu(){
document.getElementById("myDropdown").classList.toggle("show");
}