Check whether a string matches a regex in JS - javascript

I want to use JavaScript (I can also use jQuery) to do check whether a string matches the regex ^([a-z0-9]{5,})$, and get a true or false result.
match() seems to check whether part of a string matches a regex, not the whole thing. Does it solve the problem? Can I adapt it to solve the problem? How?

Use regex.test() if all you want is a boolean result:
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
...and you could remove the () from your regexp since you've no need for a capture.

Use test() method :
var term = "sample1";
var re = new RegExp("^([a-z0-9]{5,})$");
if (re.test(term)) {
console.log("Valid");
} else {
console.log("Invalid");
}

You can use match() as well:
if (str.match(/^([a-z0-9]{5,})$/)) {
alert("match!");
}
But test() seems to be faster as you can read here.
Important difference between match() and test():
match() works only with strings, but test() works also with integers.
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

Use /youregexp/.test(yourString) if you only want to know whether your string matches the regexp.

let str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
let regexp = /[a-d]/gi;
console.log(str.match(regexp));

Here's an example that looks for certain HTML tags so it's clear that /someregex/.test() returns a boolean:
if(/(span|h[0-6]|li|a)/i.test("h3")) alert('true');
Remember to indicate ^ for beginning of the string and $ for the end, if you want to test the exact match of entire string.
Example:
/[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

try
/^[a-z\d]{5,}$/.test(str)
console.log( /^[a-z\d]{5,}$/.test("abc123") );
console.log( /^[a-z\d]{5,}$/.test("ab12") );

I would recommend using the execute method which returns null if no match exists otherwise it returns a helpful object.
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]

You can try this, it works for me.
<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>

please try this flower:
/^[a-z0-9\_\.\-]{2,20}\#[a-z0-9\_\-]{2,20}\.[a-z]{2,9}$/.test('abc#abc.abc');
true

If you don't want ^ and $ around the regex (I had such a usecase) you can do something like
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`)

Update/Add
If the query string does not present in the URL then the below solution will work to add the param in the URL, if it already exists then it will update.
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}`;
}
}
}

Related

Regular Expression Pattern matching issue

Not a lot of experience in RegEx stuff.
I have the following in java script which works perfectly fine.
The following pattern is used allow only alpha numeric
var valid = /^[A-Za-z0-9]+$/.test("a"); // returns true
var valid = /^[A-Za-z0-9]+$/.test("#"); // returns false
I am using the pattern part "^[A-Za-z0-9]" in some other places of the code and was asked to use the part "^[A-Za-z0-9]" in a variable and use it so that it is not repetitive. The following is a modification to the above:
var regExPart= "^[A-Za-z0-9]";
var regExString = ("/" + regExPart+ "+$/".replace(/\"/g, "")); // replacing the quotes
var regExp = new RegExp(regExString); // results in /^[A-Za-z0-9]+$/
var valid = regExp.test(charValue); // charValue could be any keyvalue "a" or "#"
//the above returns false for "a"
//the above returns false for "#"
I am writing this in a keypress event to allow only alpha numeric
keypressValidation: function (e) {
var charCode = (e.which) ? e.which: event.keyCode;
var charValue = String.fromCharCode(charCode);
var valid = return /^[A-Za-z0-9]+$/.test(charValue);
if (!valid)
{
//prevent default (don't allow/ enter the value)
}
Not sure why. What am I missing in this. Need to return true for "a" and false for "#" for both the approaches. Any help/ suggestion would be of great help. Thank in advance.
For the RegExp class constructor, you do not need to specify forward slashes /.
var regExPart= "^[A-Za-z0-9]";
var regExp = new RegExp(regExPart + "+$"); // results in /^[A-Za-z0-9]+$/
console.log('a', regExp.test('a'))
console.log('#', regExp.test('#'))
It is not a must to contain '/'s in regexp
new RegExp("^[0-9a-zA-Z]$").test('a')
return true
new RegExp("^[0-9a-zA-Z]$").test('#')
return false
So just do
var rex="^[0-9a-zA-Z]$"
And you can use it anywhere. Tested in Chrome console.
I've made an example using your regex of what it should do, i think the way you were building your regex was not helping. You don't need to create a string and then create a new regex object , you can use /regex part/.
Anyways here is a working example.
function keypress(e) {
// Get the current typed key
var keynum = e.key;
// this regex only allow character between a and z and 0 and 9
var regex = /^[a-zA-Z0-9]+$/;
// we check if the current key matches our regex
if(!keynum.match(regex) ) {
// it doesn't ? well we stop the event from happening
e.preventDefault();
}
}
<input type="text" onkeypress="keypress(event)">

Javascript regex to replace "split"

I would like to use Javascript Regex instead of split.
Here is the example string:
var str = "123:foo";
The current method calls:
str.split(":")[1]
This will return "foo", but it raises an Error when given a bad string that doesn't have a :.
So this would raise an error:
var str = "fooblah";
In the case of "fooblah" I'd like to just return an empty string.
This should be pretty simple, but went looking for it, and couldn't figure it out. Thank you in advance.
Remove the part up to and including the colon (or the end of the string, if there's no colon):
"123:foo".replace(/.*?(:|$)/, '') // "foo"
"foobar" .replace(/.*?(:|$)/, '') // ""
How this regexp works:
.* Grab everything
? non-greedily
( until we come to
: a colon
| or
$ the end of the string
)
A regex won't help you. Your error likely arises from trying to use undefined later. Instead, check the length of the split first.
var arr = str.split(':');
if (arr.length < 2) {
// Do something to handle a bad string
} else {
var match = arr[1];
...
}
Here's what I've always used, with different variations; this is just a simple version of it:
function split(str, d) {
var op = "";
if(str.indexOf(d) > 0) {
op = str.split(d);
}
return(op);
}
Fairly simple, either returns an array or an empty string.
var str1 = "123:foo", str2 = "fooblah";
var res = function (s) {
return /:/.test(s) && s.replace(/.*(?=:):/, "") || ""
};
console.log(res(str1), res(str2))
Here is a solution using a single regex, with the part you want in the capturing group:
^[^:]*:([^:]+)

Determining whether a string has a substring (word)

I try to use a conditional to verify if a string contain a certain word, for example:
I want to use a method (regex?) to find if a string has the text "&SWE>clickable".
var text1 = "layer_legs";
var text2 = "layer_head&SWE>clickable";
if (....)
document.write ("the layer is clickable")
else
document.write ("the layer is not clickable")
How can I do that?
You can use String.indexOf. It returns -1 if the string is not found, otherwise it returns the index where the string was found. You can use it like this:
if (s.indexOf("&SWE>clickable") !== -1) { ... }
if (text2.indexOf("&SWE>clickable") > -1) {
....
try this :
if (text1.indexOf('&SWE>clickable')>=0){ ... }
or regex way :
var re = new RegExp('\&SWE\>clickable')
if (re.test(text1)){ ... }
if(text1.indexOf(text2))
document.write ("the layer is clickable")
else
document.write ("the layer is not clickable")
if (/&SWE>clickable/g.test(text2)) {
// exists
}
EDIT: Using indexOf like others have posted might be better, since it’s more readable and you don‘t need to escape characters. And arguably faster :/

JavaScript indexOf to ignore Case

I am trying to find if an image has in its source name noPic which can be in upper or lower case.
var noPic = largeSrc.indexOf("nopic");
Should I write :
var noPic = largeSrc.toLowerCase().indexOf("nopic");
But this solution doesn't work...
You can use regex with a case-insensitive modifier - admittedly not necessarily as fast as indexOf.
var noPic = largeSrc.search(/nopic/i);
No, there is no case-insensitive way to call that function. Perhaps the reason your second example doesn't work is because you are missing a call to the text() function.
Try this:
var search = "nopic";
var noPic = largeSrc.text().toLowerCase().indexOf(search.toLowerCase());
Note that if the search string is from user input you'll need to escape the special regexp characters.
Here's what it would look like:
var search = getUserInput();
/* case-insensitive search takes around 2 times more than simple indexOf() */
var regex = RegExp(search.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), "i");
var noPic = testString.search(regex);
See the updated jsperf: http://jsperf.com/regex-vs-tolowercase-then-regex/4
footnote: regexp escaping from https://stackoverflow.com/a/3561711/1333402
Try with:
var lowerCaseLargeSrc = largeSrc.toLowerCase();
var noPic = lowerCaseLargeSrc.indexOf("nopic");
Your code will only work if largeSrc is already a string. You might be getting an input that's an html element instead. So, use jQuery to resolve any potential input element into the text that's inside it. Example:
var noPic = largeSrc.text().toLowerCase().indexOf("nopic");
How about using findIndex instead that way you can do all your toLowerCase() inside the callback. Worked great for me:
// Not Supported in IE 6-11
const arr = ['HELLO', 'WORLD'];
const str = 'world';
const index = arr.findIndex(element => {
return element.toLowerCase() === str.toLowerCase();
});
console.log(index); // 👉️ 1
if (index !== -1) {
// 👉️ string is in the array
}
Credit:
https://bobbyhadz.com/blog/javascript-make-array-indexof-case-insensitive

Get everything after the dash in a string in JavaScript

What would be the cleanest way of doing this that would work in both IE and Firefox?
My string looks like this sometext-20202
Now the sometext and the integer after the dash can be of varying length.
Should I just use substring and index of or are there other ways?
How I would do this:
// function you can use:
function getSecondPart(str) {
return str.split('-')[1];
}
// use the function:
alert(getSecondPart("sometext-20202"));
A solution I prefer would be:
const str = 'sometext-20202';
const slug = str.split('-').pop();
Where slug would be your result
var testStr = "sometext-20202"
var splitStr = testStr.substring(testStr.indexOf('-') + 1);
var the_string = "sometext-20202";
var parts = the_string.split('-', 2);
// After calling split(), 'parts' is an array with two elements:
// parts[0] is 'sometext'
// parts[1] is '20202'
var the_text = parts[0];
var the_num = parts[1];
With built-in javascript replace() function and using of regex (/(.*)-/), you can replace the substring before the dash character with empty string (""):
"sometext-20202".replace(/(.*)-/,""); // result --> "20202"
AFAIK, both substring() and indexOf() are supported by both Mozilla and IE. However, note that substr() might not be supported on earlier versions of some browsers (esp. Netscape/Opera).
Your post indicates that you already know how to do it using substring() and indexOf(), so I'm not posting a code sample.
myString.split('-').splice(1).join('-')
I came to this question because I needed what OP was asking but more than what other answers offered (they're technically correct, but too minimal for my purposes). I've made my own solution; maybe it'll help someone else.
Let's say your string is 'Version 12.34.56'. If you use '.' to split, the other answers will tend to give you '56', when maybe what you actually want is '.34.56' (i.e. everything from the first occurrence instead of the last, but OP's specific case just so happened to only have one occurrence). Perhaps you might even want 'Version 12'.
I've also written this to handle certain failures (like if null gets passed or an empty string, etc.). In those cases, the following function will return false.
Use
splitAtSearch('Version 12.34.56', '.') // Returns ['Version 12', '.34.56']
Function
/**
* Splits string based on first result in search
* #param {string} string - String to split
* #param {string} search - Characters to split at
* #return {array|false} - Strings, split at search
* False on blank string or invalid type
*/
function splitAtSearch( string, search ) {
let isValid = string !== '' // Disallow Empty
&& typeof string === 'string' // Allow strings
|| typeof string === 'number' // Allow numbers
if (!isValid) { return false } // Failed
else { string += '' } // Ensure string type
// Search
let searchIndex = string.indexOf(search)
let isBlank = (''+search) === ''
let isFound = searchIndex !== -1
let noSplit = searchIndex === 0
let parts = []
// Remains whole
if (!isFound || noSplit || isBlank) {
parts[0] = string
}
// Requires splitting
else {
parts[0] = string.substring(0, searchIndex)
parts[1] = string.substring(searchIndex)
}
return parts
}
Examples
splitAtSearch('') // false
splitAtSearch(true) // false
splitAtSearch(false) // false
splitAtSearch(null) // false
splitAtSearch(undefined) // false
splitAtSearch(NaN) // ['NaN']
splitAtSearch('foobar', 'ba') // ['foo', 'bar']
splitAtSearch('foobar', '') // ['foobar']
splitAtSearch('foobar', 'z') // ['foobar']
splitAtSearch('foobar', 'foo') // ['foobar'] not ['', 'foobar']
splitAtSearch('blah bleh bluh', 'bl') // ['blah bleh bluh']
splitAtSearch('blah bleh bluh', 'ble') // ['blah ', 'bleh bluh']
splitAtSearch('$10.99', '.') // ['$10', '.99']
splitAtSearch(3.14159, '.') // ['3', '.14159']
For those trying to get everything after the first occurrence:
Something like "Nic K Cage" to "K Cage".
You can use slice to get everything from a certain character. In this case from the first space:
const delim = " "
const name = "Nic K Cage"
const result = name.split(delim).slice(1).join(delim) // prints: "K Cage"
Or if OP's string had two hyphens:
const text = "sometext-20202-03"
// Option 1
const opt1 = text.slice(text.indexOf('-')).slice(1) // prints: 20202-03
// Option 2
const opt2 = text.split('-').slice(1).join("-") // prints: 20202-03
Efficient, compact and works in the general case:
s='sometext-20202'
s.slice(s.lastIndexOf('-')+1)
Use a regular expression of the form: \w-\d+ where a \w represents a word and \d represents a digit. They won't work out of the box, so play around. Try this.
You can use split method for it. And if you should take string from specific pattern you can use split with req. exp.:
var string = "sometext-20202";
console.log(string.split(/-(.*)/)[1])
Everyone else has posted some perfectly reasonable answers. I took a different direction. Without using split, substring, or indexOf. Works great on i.e. and firefox. Probably works on Netscape too.
Just a loop and two ifs.
function getAfterDash(str) {
var dashed = false;
var result = "";
for (var i = 0, len = str.length; i < len; i++) {
if (dashed) {
result = result + str[i];
}
if (str[i] === '-') {
dashed = true;
}
}
return result;
};
console.log(getAfterDash("adfjkl-o812347"));
My solution is performant and handles edge cases.
The point of the above code was to procrastinate work, please don't actually use it.
To use any delimiter and get first or second part
//To divide string using deimeter - here #
//str: full string that is to be splitted
//delimeter: like '-'
//part number: 0 - for string befor delimiter , 1 - string after delimiter
getPartString(str, delimter, partNumber) {
return str.split(delimter)[partNumber];
}

Categories

Resources