.replace() is not working like it should - javascript

I am trying to toggle a hidden input element when the select element has a certain option. When I am alerted of variable q, q has no input but variable put does I am quite confused as to why .replace() removes the entire string.
function hiddeninput(choice, put) {
var q = put.replace(/./g, "").replace(/#/g, "");
alert(put + "," + q);//alerts .other,
if (choice === q) {
$(put).show();
} else {
$(put).hide();
}
}
Any help would be appreciated. JSfiddle has been quite buggy these past few days some of my previous working fiddles have stopped working, maybe that could be the reason.

Do you realize that . is to match any character?
You need to escape it with a \ so it will match just the . and not any character.
var q = put.replace(/\./g, "").replace(/#/g, "");
And instead of doing two replacements you can just do one
var q = put.replace(/[.#]/g,"");

In regex "." will match any character. You've got: put.replace(/./g, "");. This means you're replacing each match of any character with nothing, which will result in nothing.
If you want to match a dot, you need to escape the special character using a backslash: put.replace(/\./g, "");.
I'm not sure if this'll entirely solve your problem, but to me it seems like something unintended.

Related

ASCII character not being recognized in if statement

I am trying to get a string from a html page with jquery and this is what I have.
var text = $(this).text();
var key = text.substring(0,1);
if(key == ' ' || key == ' ')
key = text.substring(1,2);
text is this  Home
And I want to skip the space and or the keycode above It appears this code does not work either. It only gets the text.substring(0,1); instead of text.substring(1,2); because the if statement is not catching.= and I am not sure why. Any help would be super awesome! Thanks!
There are several problems with the code in the question. First,   has no special meaning in JavaScript: it is a string literal with six characters. Second, text.substring(1,2) returns simply the second character of text, not all characters from the second one onwards.
Assuming that you wish to remove one leading SPACE or NO-BREAK SPACE (which is what   means in HTML; it is not an Ascii character, by the way), then the following code would work:
var first = text.substring(0, 1);
if(first === ' ' || first === '\u00A0') {
text = text.substring(1, text.length);
}
The notation \u00A0 is a JavaScript escape notation for NO-BREAK SPACE U+00A0.
Should you wish to remove multiple spaces at the start, and perhaps at the end too, some modifications are needed. In that case, using a replace operation with regular expression is probably best.
If you want remove spaces at the beginning (and end) of a string, you can use the trim function
var myvar = " home"
myVar.trim() // --> "home"
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim

Regex is confusing me and why won't it parse properly?

Sorry about the confusing title. I'm new to Regex and JS/JQ in general. However, I'm trying to parse this. Basically, I want it to add the key pressed to the HTML if and ONLY if the keys 0-9 and the keys +, -, /, and * are pressed. Any help would be much appreciated. Here is my code:
function charCode(code) {
return String.fromCharCode(code);
}
function escapeChars(esc) {
return esc.replace(/[0-9\+-\*\/]*$/, "");
}
$('#tb').html("0");
$(document).on("keydown", function(event) {
var div = $('#tb');
var which = event.which;
which = charCode(which);
which = escapeChars(which);
else if (div.html() == "0") {
//alert("Div is equal to 0."); --Debug
div.html(which);
} else {
//alert("Div is equal to " + div.html()); --Debug
div.html(div.html() + which);
}
});
Currently, it doesn't allow anything through.
There's a couple problems with your regular expression.
You want to replace characters that do not match your list. To do that, you start your character class ([]) with a ^.
You don't need to escape + or * in the regular expression. You do need to move the - to the beginning or end though.
You don't need the * or the $ after the character class. Dropping those, you'll replace any character that doesn't match, no matter where it occurs in the string.
In case your string contains more than one character (may not apply here), adding a g flag to the end will allow you to replace all characters that do not match.
That results in a regular expression that looks like this:
/[^0-9+*\/-]/g
This fiddle shows the above regular expression working: http://jsfiddle.net/WyttT/
Updated
Another problem you're encountering is caused by checking keycodes from a keydown event. The keycodes on keydown do not match to actual ascii character codes, so non-alphanumeric keys are getting converted into weird characters. If you change your even handler to respond tokeypress instead, you'll get better results.
I don't think you want a regex for this. I think charAt() will do what you want far more simply.
You have a character. You have a list of characters which either match it or don't. charAt() does that simply and efficiently.
Now that jcsanyi has helped you with the regex, here is a simplification of your JS code. Codepen
You will want to use keypress instead of keydown/keyup, otherwise your numpad will return the wrong keys, and anything requiring a shift (shift+8 = * for instance) won't work. You can also use RegExp.test(String) to check if the character is valid, and div.append(char) in place of div.html(div.html + char).
var div = $('#tb');
$(document).on("keypress", function(event) {
var char = String.fromCharCode(event.which);
if (/[0-9+*\/-]/.test(char) === true) {
div.append(char);
}
});

Javascript Regular expression to remove unwanted <br>,

I have a JS stirng like this
<div id="grouplogo_nav"><br> <ul><br> <li><a class="group_hlfppt" target="_blank" href="http://www.hlfppt.org/">&nbsp;</a></li><br> </ul><br> </div>
I need to remove all <br> and $nbsp; that are only between > and <. I tried to write a regular expression, but didn't got it right. Does anybody have a solution.
EDIT :
Please note i want to remove only the tags b/w > and <
Avoid using regex on html!
Try creating a temporary div from the string, and using the DOM to remove any br tags from it. This is much more robust than parsing html with regex, which can be harmful to your health:
var tempDiv = document.createElement('div');
tempDiv.innerHTML = mystringwithBRin;
var nodes = tempDiv.childNodes;
for(var nodeId=nodes.length-1; nodeId >= 0; --nodeId) {
if(nodes[nodeId].tagName === 'br') {
tempDiv.removeChild(nodes[nodeId]);
}
}
var newStr = tempDiv.innerHTML;
Note that we iterate in reverse over the child nodes so that the node IDs remain valid after removing a given child node.
http://jsfiddle.net/fxfrt/
myString = myString.replace(/^( |<br>)+/, '');
... where /.../ denotes a regular expression, ^ denotes start of string, ($nbsp;|<br>) denotes " or <br>", and + denotes "one or more occurrence of the previous expression". And then simply replace that full match with an empty string.
s.replace(/(>)(?: |<br>)+(\s?<)/g,'$1$2');
Don't use this in production. See the answer from Phil H.
Edit: I try to explain it a bit and hope my english is good enough.
Basically we have two different kinds of parentheses here. The first pair and third pair () are normal parentheses. They are used to remember the characters that are matched by the enclosed pattern and group the characters together. For the second pair, we don't need to remember the characters for later use, so we disable the "remember" functionality by using the form (?:) and only group the characters to make the + work as expected. The + quantifier means "one or more occurrences", so or <br> must be there one or more times. The last part (\s?<) matches a whitespace character (\s), which can be missing or occur one time (?), followed by the characters <. $1 and $2 are kind of variables that are replaces by the remembered characters of the first and third parentheses.
MDN provides a nice table, which explains all the special characters.
You need to replace globally. Also don't forget that you can have the being closed . Try this:
myString = myString.replace(/( |<br>|<br \/>)/g, '');
This worked for me, please note for the multi lines
myString = myString.replace(/( |<br>|<br \/>)/gm, '');
myString = myString.replace(/^( |<br>)+/, '');
hope this helps

jQuery input filter for textarea

I adapted this solution into my script. The idea is to prevent the user from typing unauthorized characters (of course there is also a filter on the back end).
$('#someinput').keyup(function() {
var $th = $(this);
$th.val( $th.val().replace(/[^a-zA-Z0-9]/g, function(str) {
console.log(str);
return '';
}))
})
It works nice, but I also need the users to be able to type specific allowed characters like: .,!?ñáéíóú - I mean, the basic a-zA-Z0-9 plus some basic chars and the whole bunch of special language characters.
What actually needs to be left out are: ##$%^&*()=_+"':;/<>\|{}[]
Any ideas? Thanks!
Solution thanks to Michael
//query
$('#someinput').keyup(function() {
var $th = $(this);
$th.val($th.val().replace(/[##$%\^&*()=_+"':;\/<>\\\|{}\[\]]/g,function(str){return '';}));
}).bind('paste',function(e) {
setTimeout(function() {
$('#someinput').val($('#someinput').val().replace(/[##$%\^&*()=_+"':;\/<>\\\|{}\[\]]/g,function(str){return '';}));
$('#someinput').val($('#someinput').val().replace(/\s+/g,' '));
},100);
});
Invert your regular expression to only replace the specific characters you want omitted:
$th.val( $th.val().replace(/\s?[##$%\^&*()=_+"':;\/<>\\\|{}\[\]]/g, ""));
// Edit: added optional \s to replace spaces after special chars
Note, a few of them need to be escaped with a backslash inside a [] character class: \\\[\]\^\/
If I'm understanding what you are wanting to do, can't you just add those unwanted characters to your regex instead of doing the [^a-zA-Z0-9]?
Replace that with [##\$%\^&\*\(\)=_\+"':;\/<>\\\|\{\}\[\]] (notice the escaping)

How to replace whitespaces using javascript?

I'm trying to remove the whitespaces from a textarea . The below code is not appending the text i'm selecting from two dropdowns. Can somebody tell me where i'd gone wrong? I'm trying to remove multiple spaces within the string as well, will that work with the same? Dont know regular expressions much. Please help.
function addToExpressionPreview() {
var reqColumnName = $('#ddlColumnNames')[0].value;
var reqOperator = $('#ddOperator')[0].value;
var expressionTextArea = document.getElementById("expressionPreview");
var txt = document.createTextNode(reqColumnName + reqOperator.toString());
if (expressionTextArea.value.match(/^\s+$/) != null)
{
expressionTextArea.value = (expressionTextArea.value.replace(/^\W+/, '')).replace(/\W+$/, '');
}
expressionTextArea.appendChild(txt);
}
> function addToExpressionPreview() {
> var reqColumnName = $('#ddlColumnNames')[0].value;
> var reqOperator = $('#ddOperator')[0].value;
You might as well use document.getElementById() for each of the above.
> var expressionTextArea = document.getElementById("expressionPreview");
> var txt = document.createTextNode(reqColumnName + reqOperator.toString());
reqOperator is already a string, and in any case, the use of the + operator will coerce it to String unless all expressions or identifiers involved are Numbers.
> if (expressionTextArea.value.match(/^\s+$/) != null) {
There is no need for match here. I seems like you are trying to see if the value is all whitespace, so you can use:
if (/^\s*$/.test(expressionTextArea.value)) {
// value is empty or all whitespace
Since you re-use expressionTextArea.value several times, it would be much more convenient to store it an a variable, preferably with a short name.
> expressionTextArea.value = (expressionTextArea.value.replace(/^\W+/,
> '')).replace(/\W+$/, '');
That will replace one or more non-word characters at the end of the string with nothing. If you want to replace multiple white space characters anywhere in the string with one, then (note wrapping for posting here):
expressionTextArea.value = expressionTextArea.value.
replace(/^\s+/,'').
replace(/\s+$/, '').
replace(/\s+/g,' ');
Note that \s does not match the same range of 'whitespace' characters in all browsers. However, for simple use for form element values it is probably sufficient.
Whitespace is matched by \s, so
expressionTextArea.value.replace(/\s/g, "");
should do the trick for you.
In your sample, ^\W+ will only match leading characters that are not a word character, and ^\s+$ will only match if the entire string is whitespace. To do a global replace(not just the first match) you need to use the g modifier.
Refer this link, you can get some idea. Try .replace(/ /g,"UrReplacement");
Edit: or .split(' ').join('UrReplacement') if you have an aversion to REs

Categories

Resources