0

Hi everyone...I'm very much new to java scripting..My problem is...I have a situation where I have to check wether the text entered into a text box contains "_" (underscore) or not..I have to use this in javascript of my asp.net page. can anyone help me with some code..??

4
Contributors
3
Replies
4
Views
6 Years
Discussion Span
Last Post by Taywin
0

To check if a string contains a specific character or set of characters in JavaScript use indexOf().

Syntax: string.indexOf(searchstring) Example:

str="hello word";
if (str.indexOf("_")>0){
	alert("Has underscore");
}
else{
        alert("Does not have underscore");
}

The str variable would take the data from the textbox. The indexOf() function returns to position of the character if present in the string or returns a -1 if not present.

Hope this helps and all the best.

Edited by sudeepjd: n/a

0

Another simple built-in function is match(). It is similar to indexOf() but it returns a boolean instead. If it found the pattern (string or regexp), it will return true; otherwise, it will return false.

if("hasNoUnderscore".match(/_/)) { alert("Yes") } //  use regexp to match
else { alert("No") }
if("hasNoUnderscore".match("_")) { alert("Yes") } //  use string pattern to match
else { alert("No") }

if("has_underscore_more".match(/_/)) { alert("Yes") }  // use regexp to match
else { alert("No") }
if("has_underscore_more".match("_")) { alert("Yes") }  // use string pattern to match
else { alert("No") }

Edited by Taywin: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.