regex special characters javascript code example

Example 1: regex special characters javascript

var regex = /^[a-zA-Z0-9!@#\$%\^\&*\)\(+=._-]+$/g

Example 2: javascript escape regex

function escapeRegExp(input) {
	const source = typeof input === 'string' || input instanceof String ? input : '';
	return source.replace(/[-[/\]{}()*+?.,\\^$|#\s]/g, '\\$&');
}

Example 3: javascript have special characters

var format = /[ `!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~]/;
//            ^                                       ^   
document.write(format.test("My@string-with(some%text)") + "<br/>");
document.write(format.test("My string with spaces") + "<br/>");
document.write(format.test("MyStringContainingNoSpecialChars"));

Example 4: regular expression javascript

// Tests website Regular Expression against document.location (current page url)
if (/^https\:\/\/example\.com\/$/.exec(document.location)){
	console.log("Look mam, I can regex!");
}

Tags:

Java Example