I don't know why search() function returns 0 for any input with SPECIAL CHARACTER, I wanted to find position of 1st occurrence of special character. When I am hardcoding the value for search() method it is working fine, but when I am taking value from text box it is not working properly.
Following is my HTML code:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript" src="jquery-1.6.4.min.js"></script>
<script type="text/javascript" src="test.js"></script>
</head>
<body>
<input type="text" id="txt" onkeyup="return checkLength();"/>
<input type="button" id="btn" value="Verify" onclick="getValue()"/>
</body>
</html>
Following is the script where I have implemented the use of search() of Javascript, but don't know why I am getting 0 value for any input. Actually I wanted to find the position of first special character occurrence.
$(document).ready(function() {
$('#btn').attr('disabled',true);
$("#txt").bind({
paste : function(){
$('#btn').attr('disabled',false);
checkLength();
},
cut : function(){
checkLength();
}
});
});
function checkLength(){
var txtLength = $("#txt").val().length;
var banTxt = document.getElementById("txt").value;
if (txtLength != 0) {
if(isAlphaNumeric(document.getElementById("txt").value)) {
$('#btn').attr('disabled',false);
} else {
var str=banTxt;
//Here I am using search() to find position of Special Character.
var n=banTxt.search(/[^a-zA-Z ]/g);
alert("position of special char is: " + n);
var preTxt = banTxt.substring(0,(txtLength - 1));
var preTxtLength = preTxt.length;
alert("Special characters are not allowed!");
if(preTxtLength == 0){
$('#btn').attr('disabled',true);
document.getElementById("txt").value = "";
}else if(preTxtLength != 0){
document.getElementById("txt").value = preTxt;
$('#btn').attr('disabled',false);
}
}
} else {
$('#btn').attr('disabled',true);
}
}
function isAlphaNumeric(inputString) {
return inputString.match(/^[0-9A-Za-z]+$/);
}
function getValue(){
var txtValue = document.getElementById("txt").value;
alert("Value submitted is: " + txtValue);
}
var n=banTxt.search(/[^a-zA-Z ]/g);
I tried with string with special characters like 123#4$5 , 12#4 , etc. and I am getting alert as position of special char is: 0
That's just what your regex matches: No alphabet characters and no blanks - that includes digits. In contrast, your isAlphaNumeric function matches against /^[0-9A-Za-z]+$/ - you probably want to align them with each other.
Actually i have used the following line var n=banTxt.search(/[^a-zA-Z ]/g); for getting the position of special char, at the same time please note that i have used onkeyup event so if i am copy pasting the code i.e first ctrl then v, ctrl + v then ctrl itself is keyup event i think this might be the reason i am getting 0 as position of special char, as after pressing ctrl no text is pasted but onkeyup event is triggered.
I am looking for the solution of it.
Related
I have a paragraph from which i want to delete a complete one string when user press single backspace.
For example like in yahoo mail. when we compose an email and write email address at "To or CC or BCC" section(s), when user press single backspace the complete email address is deleted.
I want that functionality but in paragraph.
Removing e-mail addresses on backspace is just a deletion of characters until you hit a space (or ; depends on your use case) char.
So basically what you are really asking here is:
How to substring the last portion of a string while the space character is the delimiter.
Here is a simple snippet as example:
EDIT:
I've updated the snippet to support caret (cursor) position while clicking the backspace or delete keys.
$('#delete').on('click', function(){
var $input = $('#mystring');
var nextStr = deleteUpToSpace($input.val());
$input.val(nextStr);
});
$('#mystring').on('keyup', function(e){
var currentCursorPoisitoin = this.selectionStart;
if(e.keyCode == 8 || e.keyCode == 46){ // backspace or delete keys
var $input = $(this);
var nextStr = deleteBasedOnPosition($input.val(), currentCursorPoisitoin);
$input.val(nextStr);
}
});
function deleteUpToSpace(str){
var index = str.lastIndexOf(" ");
var nextStr = str.substring(0, index);
return nextStr;
}
function deleteBasedOnPosition(str, position){
var strUpToPosition = str.slice(0, position);
var lastIndexOfSpace = strUpToPosition.lastIndexOf(" ");
var strToRemove = strUpToPosition.substring(lastIndexOfSpace, position);
var nextStr = str.replace(strToRemove, "");
return nextStr;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="mystring" value="this is a test string">
<button id="delete">Delete</button>
You probably want to remove a word when backspace is clicked.
You can use this code.
<!doctype html>
<html>
<head>
<title>Test</title>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
</head>
<body>
<textarea id="foo"></textarea>
<script type="text/javascript">
document.getElementById('foo').addEventListener("keydown",function(event){
if(event.code=="Backspace"){
var text=document.getElementById('foo').value;
var lastspace = text.lastIndexOf(" ");
var updateStr=text.substring(0,lastspace);
document.getElementById('foo').value=updateStr;
}
});
</script>
</body>
</html>
Firstly, you need to identify the separator that separates these different entities. For instance, if you need to remove the last sentence in a paragraph, the separator is the period (or full-stop, as some may call it).
Then, you can split the string by the separator, remove the last two elements (because the last element is essentially a non-completed) and then rejoin.
text.split('.').slice(0,-2).join('.') + '.'
If your separator was a period. Or generally,
text.split(separator).slice(0,-2).join(separator) + separator
See this JS Fiddle I made for demonstration: https://jsfiddle.net/tt24kfng/1/
An interesting thing you could try out would be to remove the last completed entity and keeping the last incompleted intact.
I posted a question earlier regarding a school problem I was working on. I have what I believe to be the correct function per the assignment, but I am stuck. I need to have the alert() in my code display the index position of the substring it is searching for. Everything else works but I don't know how to send that info back to a variable that I can print to the screen. My code is as follows:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Lesson 6 Application Project A</title>
<script language="JavaScript" type=text/javascript>
<!--
/*****************************************************************************
The placeholders sub and string are used to pass as arguments the
user's entry into the text box and the textarea. The variable where
is assigned the result of a method which returns the index (integer)
of the first occurence of sub (the string the program is searching for).
Start the search at the beginning of string (the text that is being searched).
Since the string is zero based, add 1 is to get the correct position of sub.
*****************************************************************************/
function search(sub, string) {
var where;
if (string.search(sub) != -1){
where = alert("Your index position is: " + where);
}
else{
where = alert("Could not find your string!");
}
}
//-->
</script>
</head>
<body>
<h3>CIW JavaScript Specialist</h3>
<hr />
<form name="myForm">
<p>
<strong>Look for:</strong>
<input type="text" name="what" size="20" />
</p>
<p>
<strong>in this string:</strong>
<textarea name="toSearch" rows="4" cols="30" wrap="virtual">
</textarea>
</p>
<p>
<input type="button" value="Search"
onclick="search(myForm.what.value, myForm.toSearch.value);" />
</p>
</form>
</body>
</html>
Try this
function search(sub, string) {
var where = string.indexOf(sub);
if (where != -1){
alert("Your index position is: " + where);
}
else{
alert("Could not find your string!");
}
}
Your where variable should be assinged to the result of the search.
function search(sub, string) {
var where = string.search(sub);
if (where != -1){
alert("Your index position is: " + (where + 1));
}
else{
alert("Could not find your string!");
}
}
My solution to my own problem was to create a variable called position and set it to receive the index position of the substring. I could then add that into my alert() and display the results to the screen. Corrected code is as follows:
function search(sub, string) {
var where;
var position = string.search(sub);
if (string.search(sub) != -1){
where = alert("Your index position is: " + position);
}
else{
where = alert("Could not find your string!");
}
}
I am calling .keyup function of Search Textbox, and in that keyup(), I am refreshing the GRID from the database.
Problem:
But the grid is getting refreshed for (special keys too ) arrow keys, number lock,function keys and all other keys and refreshing for those keys are unnecessary. Except backspace, return,tab,space,delete.
I want to construct a regular expression such that it filters out all the control keys.
Sample code:
$('#searchContent').keyup(function (e) {
var key = e.which;
if ( /*condition*/ ) {
return;
}
//my code goes here...
}
What I have done:
Searched net thoroughly and I came up with hotkey, but that doesn't solved my purpose. So, any smart regular expression are there?
Try this HTML to see which codes match up with which keys (taken from Mozilla):
<html>
<head>
<title>charCode example</title>
<script type="text/javascript">
function showChar(e)
{
alert("Key Pressed: " + String.fromCharCode(e.charCode) + "\n"
+ "charCode: " + e.charCode);
}
</script>
</head>
<body onkeypress="showChar(event);">
<p>Press any 'character' type key.</p>
</body>
</html>
Try this trick:
function checkForChanges(){
var txt = $('#searchContent');
if(txt.val() != txt.attr('xvalue') {
//do referesh grid content here
}
}
$('#searchContent').keyup(function (e) {
$(this).attr('xvalue') = this.value;
clearTimeout(this.changeTimer);
this.changeTimer = setTimeout(checkForChanges, 20);
}
I am trying to make a function to split a sentence into words then split the words into characters and capitalize the first letter of each word. Yes it's homework and after many tries I can not get it to work. One thing tripping me up is using split() twice.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<head>
<title>Sentence Case Conversion</title>
<script type= "text/javascript">
/* <![CDATA[ */
/* ]]> */
</script>
</head>
<body>
<form name= "convertText">
<p>Enter text to convert to sentence case:</p>
<input type ="text" size ="120" name="userInput">
</br>
</br>
<input name= "Submit" onclick= "sentenceCase()" value= "Convert Text" type= "button">
</form>
</br>
</br>
</br>
<form name= "ouputText">
<p>Here is your converted text:</p>
<input type="text" size="120" name="result">
<script type= "text/javascript">
/* <![CDATA[ */
function sentenceCase() {
var userInput = document.forms[0].userInput.value; //get user input
var wordArray = userInput.split(" "); //split user input into individual words
for (var i=0; i<wordArray.length; i++) {
var characterArray = wordArray[i].split("");
characterArray[0].toUpperCase();
wordArray[i]=characterArray.join;
}
/* ]]> */
</script>
</body>
</html>
You're close:
> characterArray[0].toUpperCase();
That returns a value, it doesn't modify it in place
> wordArray[i]=characterArray.join;
join is a method, you have to call it. Also, it returns a value, it doesn't modify anything in place. You might consider using substring instead, but with the array you have:
var firstChar = characterArray.shift().toUpperCase();
var newWord = firstChar + characterArray.join('');
should do the trick.
toUpperCase() can't modify your variable in place; it returns the capitalized string. So:
characterArray[0] = characterArray[0].toUpperCase();
... but you could just use charAt() and substring(), too:
wordArray[0] = wordArray[0].charAt(0).toUpperCase() + wordArray[0].substring(1);
... and then you have to actually call join():
wordArray[i] = characterArray.join();
... and you'd probably want to pass that an empty string, or it'll default to a comma as a separator.
The fun way is 'hello world this is camel case'.replace(/\s(\S)/g, function($0, $1) { return $1.toUpperCase(); }), though.
Factor out the common elements into understandable pieces of code:
function toCamelCase(sentence) {
var words = sentence.split(" ");
var length = words.length;
for (var i = 1; i < length; i++)
words[i] = capitalize(words[i]);
return words.join("");
}
function capitalize(word) {
return word.charAt(0).toUpperCase() + word.slice(1);
}
Now you can convert sentences to upper case. It's probably a good idea to remove punctuation marks from the sentence before converting it. Here are a few examples:
alert(toCamelCase("java script")); // javaScript
alert(toCamelCase("json to XML")); // jsonToXML
alert(toCamelCase("ECMA script")); // ECMAScript
The last one appears to be PascalCase but is still considered valid camelCase. You can see the demo here: http://jsfiddle.net/GhKmf/
Why is this code working? I want to take the input variable and getting the emails out of it. It's not working though. Can someone help me?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
var email = /[a-z0-9\.&%]+#(?:[a-z1-9\-]+\.)+[a-z]{2,4}/i;
var input = "hi4d#gmail.com#gmail.com text here shaagd4##fdfdg.ct hefds#4564dh-dsdgd.ly";
var testout = true;
var output;
while(testout === true)
{
var execoutput = email.exec(input);
testout = email.test(input);
if(!output) {output = '';}
if(testout === true)
{
output += "<p>An email found was: " + execoutput[0] + ".</p>";
input = input.substring(execoutput[0].length);
}
}
document.write(output);
</script>
</head>
<body>
</body>
</html>
Try this: (on jsfiddle)
var email = /[a-z0-9\.&%]+#(?:[a-z0-9\-]+\.)+[a-z]{2,4}/i;
var input = "hi4d#gmail.com#gmail.com text here shaagd4##fdfdg.ct hefds#4564dh-dsdgd.ly";
var output = '';
for (;;) {
var execoutput = email.exec(input);
if (!execoutput) {
break;
}
output += "<p>An email found was: " + execoutput[0] + ".</p>";
input = input.substring(execoutput.index + execoutput[0].length);
}
document.write(output);
Note a few problems I've corrected:
The regex did not match the 0 character in the domain part. None of your input strings contained this character in the domain part, but it was a bug nonetheless.
You can't just pull off the first N characters of the input string when N is the length of the matched string, because it may not have matched at position 0. You have to add the index of the match too, or you might match the same address multiple times.
As mentioned in the comment, the code works.
It should however be duly noted I just slapped your code straight into my current project (Yay for messing up stuff!) and it works just fine there too.
HOWEVER it does not LOOK right, nor provide the correct output I suspect you want.