Javascript tab character removal - javascript

I need to remove tab characters within text inputted into particular fields of a web interface. The problem seems to be that when this happens the resulting text now contains spaces where the tabs were.
I tried using the regex : vVal = vVal.replace(/(\s+)/, ""); but using the example input 11111[tab], the value becomes 11111[space].
I dont know how this could be..

\s matches any whitespace that includes space also.
For tab try \t with global switch:
vVal = vVal.replace(/\t+/g, "");

Related

HTML Title tooltip gets cut off after spaces

I'm trying to get some specific title text to display via JavaScript, but I'm having some issues getting the entire string to show up.
The text I'm trying to display:
mechanical : Failed to copy
And here's what shows up in HTML:
`<td title="mechanical" :="" failed="" to="" copy="">mechanical : Failed to copy</td>`
The actual title displayed afterwards is just mechanical.
In Javascript:
var copyResult = json_obj[i].CopyResult; //variable that contains the text
copyResult = copyResult.replace(/["{}]/g, " "); //regex that removes some characters and replaces them with spaces
The copyResult variable is then added to the element I want.
It looks like having spaces "ends" the title attribute, so the browser tries to make more attributes with the remaining text.
What's the best way to fix this?
I was able to create a workaround. Since any space would end the title attribute, I simply used a regex to properly escape all of the space characters for the copyResult variable.
var copyResult = copyResult.replace(/[ ]/g,"\u00a0")
\u00a0 is the Unicode character for NO-BREAK-SPACE.
it's not the spaces ending the atribute, its the quotation marks... try escaping them with backslashes like \"

How to prevent white space only from going to the database?

I have this JavaScript code that only allows users to enter letters and white space. If I allow that, the user can now enter the name as white space only and it will go to the database. Is there a way to prevent the user from entering white space only and force them to add letters?
And an optional question, can I prevent the user from entering two white spaces?
<script>
function lettersOnly(input) {
var regex = /[^a-z & " "]/gi;
input.value = input.value.replace(regex, "");
}
</script>
<input id="fullname" placeholder="fullname" onkeyup="lettersOnly(this)">
You could just leave your code as is and when the user submits the form, you get rid of any whitespace. Something like:
string.replace(/\s/g,'')
The \s character matches ANY number of whitespaces, so that also solves your problem of preventing the user from entering two or more whitespaces.
However, if having whitespace in the name is a real problem, you should consider doing this on the back-end, to prevent the possibility of people bypassing your regex replace and inserting unwanted values into the DB.
Try this regex, and it will allow for one whitespace only. Otherwise, it will be removed.
var regex = /\s\s+/gi;
input.value = input.value.replace(regex, "");
And if you need to remove all whitespaces, you can try
input.value.replace(/\s/g,'')
Just add a following check condition before invoking service.
input.trim() !=== ""
It's possible to pretty easily prevent only whitespace, use .charAt() to check if the first character is whitespace.
if the entire string is whitespace, then your first character is definitely whitespace.
Example:
if (input.value.charAt(0) == " ") {
//Do your things
}
As far as checking whether or not two immediately adjacent spaces are present, you can do that with regEx relatively easily, using an expression like [ ]{2,}.
In all seriousness, you're probably better off using a well-known, predefined form-validation library for the time being.
To avoid only white spaces given as input
Just add the following check condition
If ( input.trim() == "" ){
Expression
}

error in parsing web page using javascript

I am trying to parse a page using javascript this is part of page:
<div class="title">
<h1>
Affect and Engagement in Game-BasedLearning Environments
</h1>
</div>
This is link tom page source:view-source:http://ieeexplore.ieee.org/xpl/articleDetails.jsp?tp=&arnumber=6645369?tp=&arnumber=6645369
I am using this:
$(data).find('h1').each(function()
{console.log($(this).text());
});
Now I am able to get the value inside header but the value displayed have lots of space in front and back.I tried to replace the whitespace by using replace function but replce isn't happening.I don't understand what is there in front and back of the value of header.I somehow want to remove the extra space.
Replace only replaces the first instance found, it might have only removed one space... try this instead, using regular expression syntax:
text.replace(/ /g, '');
This should remove all spaces, even the ones inside your string text. To avoid this, you may only want to replace double spaces instead:
text.replace(/ /g, '');
Also you may want to remove new lines:
text.replace(/\n/g, '');
Here is an example JSFiddle
If you know for sure that your string is only surrounded on either end by spaces, but you want to preserve everything inside, you can use trim:
text.trim();
Since your already using jQuery, you can take advantage of their $.trim function which removes leading and trailing whitespace.
$(data).find('h1').each(function() {
console.log($.trim($(this).text()));
});
Reference: $.trim()
Try using Javascript's Trim() to get rid of the whitespaces that's present on both sides.
Function's Reference:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim
Your HTML actually contains these paces within your <h1> element, so it is to be expected that they are present in the result of .text().
Normally you'd just use .trim(). However, you'll likely want to replace line breaks inside the text as well.
$(data).find('h1').each(function() {
var text = $(this).text();
// Replaces any multiple whitespace sequences with a single space.
// Even inside the text.!
// E.g. " \r\n \t" -> " "
text = text.replace(/\s+/g, " ");
// Trim leading/trailing whitespace.
text = text.trim();
console.log(text);
});
Fiddle for your pleasure.

Jquery replace not working over the entire input text

I have a text box on a HTML page, the idea is that the user can enter any text into the box and then Jquery will remove every other than letters of the alphabet.
This is what I have come up with, it works for small text samples, 1-2 lines, however anything over this it only works on a small section of the input text, is there a better way to do this?
$("#read").change(function () {
read = $("#read").val().toLowerCase().replace(/[^a-z]+/, '');
$("#read").val(read);
});
add /gi to end of your regular expression
/[^a-z]+/gi
then it will replace all occurrences through whole string.
g (for global) and i (for ignore case)
with the comments of #Lunar this is how your code should look like
$("#read").change(function () {
$(this).val($(this).val().replace(/[^a-z]/gi, ''));
});
You need to enable the regex's global flag, so that it will replace all matches instead of just the first match.
/[^a-z]+/ig
More about JS regular expressions.

Regex to put quotes for html attributes

I have a scenario like this
in html tags, if the attributes is not surrounded either by single or double quotes.. i want to put double quotes for that
how to write regex for that?
If you repeat this regex as many times as there might be tags in an element, that should work so long as the text is fairly normal and not containing lots of special characters that might give false positives.
"<a href=www.google.com title = link >".replace(/(<[^>]+?=)([^"'\s][^\s>]+)/g,"$1'$2'")
Regex says: open tag (<) followed by one or more not close tags ([^>]+) ungreedily (?) followed by equals (=) all captured as the first group ((...)) and followed by second group ((...)) capturing not single or double quote or space ([^"'\s]) followed by not space or close tag ([^\s>]) one or more times (+) and then replace that with first captured group ($1) followed by second captured group in single quotes ('$2')
For example with looping:
html = "<a href=www.google.com another=something title = link >";
newhtml = null;
while(html != newhtml){
if(newhtml)
html = newhtml;
var newhtml = html.replace(/(<[^>]+?=)([^"'\s][^\s>]+)/,"$1'$2'");
}
alert(html);
But this is a bad way to go about your problem. It is better to use an HTML parser to parse, then re-format the HTML as you want it. That would ensure well formatted HTML wheras regular expressions could only ensure well formatted HTML if the input is exactly as expected.
Very helpful! I made a slight change to allow it to match attributes with a single character value:
/(<[^>]+?=)([^"'\s>][^\s>]*)/g (changed one or more + to zero or more * and added > to the first match in second group).

Categories