To find a character in a String has to use a includes() method in the JavaScript program. Another way to a string contains a certain character using a regular expression.
They include() method finds the “contains” character in whole string, it will return a true.
Example 1: Find a “t” character in the string.
<!DOCTYPE html>
<html>
<body>
<p id="EHS"></p>
<script>
var str = "EyeHunts JavaScript tutorial.";
var check = str.includes("t");
document.getElementById("EHS").innerHTML = check;
</script>
</body>
</html>
Output: true
Example 2: Find a “z” char in string.
<!DOCTYPE html>
<html>
<body>
<p id="EHS"></p>
<script>
var str = "EyeHunts JavaScript tutorial.";
var check = str.includes("z");
document.getElementById("EHS").innerHTML = check;
</script>
</body>
</html>
Output: false
Note: The includes() method is case sensitive, so Uppercase and Lowercase characters different.
Q: How to Javascript check if the string contains only a certain character?
Answer: Return true if a given string has only a certain character and any number of occurrences of that character.
The below example will pop-up an alert box with the result.
// checking for 's'
'ssssss' -> true
'sss s' -> false
'so' -> false
<!DOCTYPE html>
<html>
<script type="text/javascript">
window.onload = function(){
document.getElementById('button').onclick = function(e){
var a = document.getElementById("message").value;
var result = new RegExp("^[s\s]+$").test(a);
alert(result);
return false;
}
}
</script>
<body>
<div class="container">
<form action="javascript:;" method="post" class="form-inline" id="form">
<input type="text" id="message" class="input-medium" placeholder="Message" value="Hello, world!" />
<button type="button" id="button" data-action="insert">Show</button>
</form>
</div>
</body>
</html>
Output:
Q: How to check if a string contains [a-zA-Z]
characters only?
Answer: No jQuery Needed, You can use a regex:
if (str.match(/[a-z]/i)) {
// alphabet letters found
}
The i
makes the regex case-insensitive. You could also do.
/[a-z]/.test(str.toLowerCase());
Do comment if you knew any other ways or have any doubts about this tutorial.
Note: The Examples are tested on Safari browser (Version 12.0.2) and Chrome.
OS: macOS 10.14 Mojave
Code: HTML 5 Version
locale is not considered while checking for only a-z / A-Z