Nomad
Nomad

Reputation: 1100

javascript check for a special character at the beginning a string

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.

Upvotes: 1

Views: 6056

Answers (6)

nnnnnn
nnnnnn

Reputation: 150080

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.

Upvotes: 5

NoviceProgrammer
NoviceProgrammer

Reputation: 3365

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.

Upvotes: 2

dku.rajkumar
dku.rajkumar

Reputation: 18588

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

Upvotes: 1

Santanu
Santanu

Reputation: 420

Refer to below link.

javascript pattern matching

Upvotes: 1

Roman
Roman

Reputation: 10403

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.

Upvotes: 1

Mike
Mike

Reputation: 358

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.

Upvotes: 3

Related Questions