javascript check for a special character at the beginning a string - javascript

I am trying to get a value from input field.
I want to check if the string has % or * at the beginning of the string then show an alert.

if (/^[%*]/.test(document.getElementById("yourelementid").value))
alert("Where can I find a JavaScript tutorial?");
By way of explanation: the regular expression /^[%*]/ means:
^ match the beginning of the string, followed immediately by
[%*] any one of the characters inside the brackets
Testing the entered value against that regex will return true or false.

getElementById(ID).value.charAt(0);
I'm sure you can figure out the rest. Please do some research first as things like this should be really easy to find by googling it.

You can use the substring method, for example:
data.substring(0, 1) === '%'
if(data.substring(0, 1) === '%' || data.substring(0, 1) === '*')
{
alert("Not allowed");
}
or you can try the regex way.

You can do that by using the indexOf method of strings.
var s = "%kdjfkjdf";
if (s.indexOf("%") == 0 || s.indexOf("*") == 0)
{
// do something
}
You can also use regular expressions too as pointed out in #nnnnnn's answer.

Refer to below link.
javascript pattern matching

var str="%*hkfhkasdfjlkjasdfjkdas";
if(str.indexOf("%") === 0|| str.indexOf("*") === 0){
alert("true");
}
else{
alert("false");
}
please check fiddle here.
http://jsfiddle.net/RPxMS/
you can also use prototype plugin for javascript which contains method startWith.
if(str.startWith("%"))
{
// do
}
check the details in the link: click here

Related

detect whether variable contains letters or numbers javascript

I've been looking on the internet but couldn't find a proper solution to my problem.
I have two use inputs. One is Age. The other is Name.
Age must be a number. Name must be a word, containing only characters.
if(age==number $$ name == characters){
// do something
}else{
// do something else
}
I tried:
if(Math.floor(num) == num $$ Math.floor(name) != name){
// do something
}else{
// do something else
}
But no luck whastsoever.
If you know how to do this could you let me know. Thanks a lot.
The regex solution is probably the simplest given that your input will be strings anyway.
Try this:
if (/^\d+$/.test(age) && /^\D+$/.test(name)) {...}
The main difference with the ones posted above is in the ^ and $; these will make sure that the string containts only the specified character, as opposed to them containing at least one.
You could do this
if (+age==age && name!=+name) {
It checks that both conditions are verified :
age strictly contains a number
name isn't a number
But it's hard to define a strict rule for a name. Here's a name in my country : "Dupé d'Egïe"
Supposing you'd want to accept for the name only "Letters from a-z and spaces" (which is probably a bad idea), then you may do
if (+age==age && /^[a-z ]+$/.test(name)) {
To test if age contains only digits and name contains no digit, you may do
if (/^\d+$/.test(age) && /^\D+$/.test(name)) {
You could use the javascript function parseInt(value), if the result is NaN, It's not a number
if(parseInt("54")) {
console.log("It's a number");
} else {
console.log("It's not");
}

Determine Whether String Begins With Particular Letters

I am trying to determine using javascript and regex whether a string begins with certain letters. If it's true I want it do something. I am trying to find the value "window_" in a particular string.
My code is as follows:
if (div_type.match(/^\window_/)){
}
This however is returning true when it clearly doesn't contain it.
Regular expressions are overkill for this kind of string matching:
if (div_type.indexOf("window_") === 0) {
// Do something
}
If you really want to go the regex route, you can use test() instead of match() /regex_pattern/.test(string)
Example:
function run(p){
return /^window_/.test(p);
}
console.log(run("window_boo"), // true
run("findow_bar")); // false
Your use:
if ( /^window_/.test(div_type) ) {
...
}
You don't need a regex for that.
if( div_type.substr(0,"window_".length) == "window_")

How can I make javascript match the start of a string?

I have the following coce:
if (link.action === "Create") {
However my link.action could be:
Create xxxx
Is there a way I can change this match so it just checks for the start being "Create" ?
Just Check string.indexOf(string_to_check). It returns the index number for a 'string_to_check', if it exists in the string. Any in your case, you want the string start with "Create", so the index should be always 0 in your case.
So, You can try this
if (link.action.indexOf("Create") == 0) {
Use a regular expression.
if (link.action.match(/^Create/) {
}
^ is a special character: an anchor which matches only the beginning of the input.
More reading on regex in general: http://www.regular-expressions.info
link.action.slice(0,6)=="Create"
Will also work as you like as above mentioned methods. For further read String object reference in java script.

Using variable in a regex

say i have the following variables:
myId; //Email_PDF
currentHoverOnItem; //Email_PDF_english of Email_PDF_Dutch or ...
So the first value is "Email_PDF" and the second is "Email_PDF_english". What i want i when currentHoverOnItem contains myId, then something can be executed.
This is what i have so far:
var pattern = new RegExp("^/"+myId+"/$");
if (currentHoverOnItem.match(pattern))
{
//Do something
}
Is this the right way to use the regex? It should match part of the string, there can be text before or after the match.
Is this the right way to use the regex?
No! Regexes are for patterns, not for literal strings. Use indexOf
if (currentHoverOnItem.indexOf(myId) >= 0)
{
//Do something
}
Try this
var pattern = new RegExp(myId, "g");
if (currentHoverOnItem.match(pattern))
{
//Do something
}
Your pattern is "anchored", meaning that ^ and $ specifiy begin and end of your string.
To match "Email_PDF_english" in an anchored pattern you could use
^Email_PDF_(.*)$, but it won't match if your string is longer, as your comment suggests.
If it's not anchored you could test for a blank following the Email_PDF_... string, ie
Email_PDF_([^\s]*)\s+
You need not use a reg_exp here. Using indexOf will do the trick for you
if(currentHoverOnItem.indexOf(myId) != -1)
{
//Do something
}

Alphanumeric, dash and underscore but no spaces regular expression check JavaScript

Trying to check input against a regular expression.
The field should only allow alphanumeric characters, dashes and underscores and should NOT allow spaces.
However, the code below allows spaces.
What am I missing?
var regexp = /^[a-zA-Z0-9\-\_]$/;
var check = "checkme";
if (check.search(regexp) == -1)
{ alert('invalid'); }
else
{ alert('valid'); }
However, the code below allows spaces.
No, it doesn't. However, it will only match on input with a length of 1. For inputs with a length greater than or equal to 1, you need a + following the character class:
var regexp = /^[a-zA-Z0-9-_]+$/;
var check = "checkme";
if (check.search(regexp) === -1)
{ alert('invalid'); }
else
{ alert('valid'); }
Note that neither the - (in this instance) nor the _ need escaping.
This is the most concise syntax I could find for a regex expression to be used for this check:
const regex = /^[\w-]+$/;
You shouldn't use String.match but RegExp.prototype.test (i.e. /abc/.test("abcd")) instead of String.search() if you're only interested in a boolean value. You also need to repeat your character class as explained in the answer by Andy E:
var regexp = /^[a-zA-Z0-9-_]+$/;
Got stupid error. So post here, if anyone find it useful
[-\._] - means hyphen, dot and underscore
[\.-_] - means all signs in range from dot to underscore
Try this
"[A-Za-z0-9_-]+"
Should allow underscores and hyphens
try this one, it is working fine for me.
"^([a-zA-Z])[a-zA-Z0-9-_]*$"
Don't escape the underscore. Might be causing some whackness.

Categories