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..??

This is the Java forum, you might want to visit the JavaScript forum :).

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.

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") }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.