Regex to match carriage return in Javascript - javascript

I am trying to write some Javascript to hide some elements that contain only carriage returns. I appreciate that the correct way to solve this problem would be to stop these elements being created, but unfortunately that is not possible in this instance. I am trying to user a regular expression to search for the unwanted elements but am not having much luck. The function I have written is as follows:
function HideEmptyP()
{
var patt = (\\r)
for(var i = 0;i<desc[i].length;i++);
{
var desc[i] = document.getElementsByClassName('sitspagedesc');
var result[i] = patt.test(desc[i]);
if (result[i] == true)
{
desc[i].style.display='none';
}
else
{
alert("No Match!");
}
}
The error I'm getting in the Web Console is 'Syntax Error: Illegal Character'.
Grateful for any ideas on how to solve this.
Thanks in advance.

I am trying to write some Javascript to hide some elements that contain only carriage returns.
There's no need for a regular expression for that, just compare the element's innerHTML property to "\\r", e.g.:
if (demo[i].innerHTML === "\\r") {
// Remove it
}
But beware that some browsers may transform a single carriage return. You might want to check for "\\r", "\\n", and just a space. To do that, you might want to use a regular expression.
Your regular expression literal ((\\r)) is just completely invalid, it's worth reading up on them to learn the correct syntax. To write a regular expression literal in JavaScript, you use / as the delimiter. So: /\\r/. To test that a string contains only \r, \n, or space, you can use /^[\r\n ]+$/ (which requires there be at least one character that matches, and uses ^ to indicate start-of-string, and $ to indicate end-of-string):
if (demo[i].innerHTML.match(/^[\r\n ]+$/) {
// Remove it
}

The reason you are getting Syntax error is because the declaration
var patt = (\r)
is incorrect it should be somethign like var patt = '\r';
Also the whole for loop is wrong.
You should define demo before you start the for loop not inside it, and result need not be an array but just a normal variable

Your litteral seems odd.
Try var patt = /\r/;

var patt=/\n/gi
should work.
extra i flag to denote case insensitive.
g for global search.

Related

What is the regular expression to be used for the sequence of strings occured?

I have a structure of string, I need a regular expression that only picks up the numbers from the structure, and also the expression should report if the structure deviates from the mentioned rule (suppose if I missed any comma or full stop or braces etc)
The structure is - {'telugu':['69492','69493','69494'],'kannada':['72224']}
The regular expression I've tried is /\[(.*?)\]/g;
The above expression is working fine for picking only numbers from the given input, but it's not reporting for the missing of any comma, fullstop or braces etc.
var contentids = {'telugu':['69492','69493','69494'],'kannada':['72224']};
var pattern = /\[(.*?)\]/g;
while ((match = pattern.exec(contentids)) != null) {
var arrayContentids2 = new Array();
arrayContentids2 = match[1].split(",");
}
I am fetching only the numbers from the given input,but I need a validation of missing commas, fullstop, braces etc from the input.
To get all the numbers you can use a RegEx like this /\'(\d+)\'|\"(\d+)\"/g. The second part is only for numbers inside " instead of ', so you can remove this if you want.
To check the balance of braces i would use a simple counting loop and move through the input. I don't think that RegEx are the right tool for this job.
To search missing commas you could use the RegEx /([\'\"]\s*[\'\"])/g and /([\[\(\{]\d+)/g to find the tow errors in
{'telugu':['69492','69493','69494'],'kannada':[72224''72224']}
Hope this will help you

javascript : problem with regular expression

I'm trying to validate the value of an input text field with the following code:
function onBlurTexto(value) {
var regexNIT = "([a-zA-z]|[0-9]|[&#,#.ÑñáéíóúÁÉÍÓÚ\|\s])";
regexCompilado = new RegExp(regexNIT);
if (!(regexCompilado.test(value))) {
alert("Wrong character in text :(");
return false;
} else {
return true;
}
}
But when i enter this text:
!65a
the function returns true (as you can see, the "!" character does not exist in the regular expression)
I'm not an expert in regular expressions, so i think i am missing something in the building of this reg.exp.
How can i put this regular expression to work?
Thanks in advance.
EDIT
i am so sorry ... i should remove the references to the variable "regexpValidar" before posting the issue. I modified the sample. Thanks #TecBrat
You should provide the start (^) and end ($) flags to your regex. Now you are matching 65a since you have alternate sets.
This should work /^([a-zA-z]|[0-9]|[&#,#.ÑñáéíóúÁÉÍÓÚ\|\s])+$/g
Demo: https://regex101.com/r/zo2MpN/3
RegExp.test looks for a match in the string, it doesn't verify that the whole string matches the regex. In order to do the latter, you need to add start and end anchors to your regex (i.e. '^' at the start and '$' at the end, so you have "^your regex here$").
I also just noticed that your regex is currently matching only one character. You probably want to add a '+' after the parens so that it matches one or more:
"^([a-zA-z]|[0-9]|[&#,#.ÑñáéíóúÁÉÍÓÚ\|\s])+$"
This is wrong. the variable you use doesn't has anything. Try this instead.
var regexCompilado = new RegExp(regexNIT);

Regex return undefined in a JavaScript String

I have a little code snippet where I use Regular Expressions to rip off punctuation, numbers etc from a string. I am getting undefined along with output of my ripped string. Can someone explain whats happening? Thanks
var regex = /[^a-zA-z\s\.]|_/gi;
function ripPunct(str) {
if ( str.match(regex) ) {
str = str.replace(regex).replace(/\s+/g, "");
}
return str;
}
console.log(ripPunct("*#£#__-=-=_+_devide-00000110490and586#multiply.edu"));
You should pass a replacement pattern to the first replace method, and also use A-Z, not A-z, in the pattern. Also, there is no point to check for a match before replacing, just use replace directly. Also, it seems the second chained replace is redundant as the first one already removes whitespace (it contains \s). Besides, the |_ alternative is also redundant since the [^a-zA-Z\s.] already matches an underscore as it is not part of the symbols specified by this character class.
var regex = /[^a-zA-Z\s.]/gi;
function ripPunct(str) {
return str.replace(regex, "");
}
console.log(ripPunct("*#£#__-=-=_+_devide-00000110490and586#multiply.edu"));

regular expression to extract function body

I have this regexp
var bodyRegExp = /function[\\s]+[(].+[)][\\s]+{(.+)}/;
bodyRegExp.exec("module.exports = function () { /* any content */ }");
It doesn't work. Why is it broken?
It's meant to pull the body of the function statement out of the source code.
Edit:
I'm being stupid. Trying to parse javascript with a regexp is stupid.
Don't escape your backslashes. Do escape your curly braces. Your character set square bracket expressions are unnecessary. Use this instead:
var bodyRegExp = /function\s+\(.*\)\s+\{(.+)\}/;
Still, this is not a very robust expression - it won't work with multi-line functions and will give unexpected results when your function has more than one set of parens or curly braces - which seems extremely likely. But it should at least address the issues you are having.
Edit: If you are always dealing with a string that contains a function with no preceding or following statements, the solutions is quite simple. Just get everything after the first opening curly brace and before the last closing curly brace.
var fnBody = fn.substring(fn.indexOf("{") + 1, fn.lastIndexOf("}"));
If you are trying to extract a single function out of a string that contains more than just the one function, you'll need to write a whole parsing algorithm to do it. Or, if it is safe to do so, you could execute the JavaScript and get the function definition string by going var fn = module.exports.toString() and then apply the above code to that string.
Function.prototype.body=function(){
this._body=this.toString().substring(this.toString().indexOf("{") + 1, this.toString().lastIndexOf("}"));
return this._body;
};
then :
myFn.body()
Just , this call,, after that you can access to body using the attribute _body :
myFn._body
/function[\\s]+[(].+[)][\\s]+{(.+)}/
your function (/* right here is wrong */)
use are using .+ which is one or more. So you need zero or more, /function +\(.*\) +{(.+)}/
The regex you need.
This one will separately extract the arguments and the body of the function code. Returning an array of 6 items the 3rd and 5th items in the array will be the arguments and the function code body. Can be used to extract methods from objects.
You can call func.toString() then use this regex on it.
var matcharray = funcstring.match(/(function\s?)([^\.])([\w|,|\s|-|_|\$]*)(.+?\{)([^\.][\s|\S]*(?=\}))/);
var bodyRegExp = /\{(.+?)\}+$/;
console.log("module.exports = function () { /* any content */ }".match(bodyRegExp))
do you have to use exec??
This returns ["{ /* any content */ }", " /* any content */ "]
I'm surprised no one did the obvious regex-wise:
var fn = function whatever1() {
function whatever2() {
}
};
var body = (''+fn).match(/{([^]*)}[^}]*/)[1];
Output:
"
function whatever2() {
}
"
Perfectly suited for multiple lines; however, personally, I like #gilly3's answer the best, using indexOf and lastIndexOf rather than a regex for this simple case (regex may be overkill). ;)
you cannot use regular expressions to parse JavaScript language syntax because the grammar for that language is too complex for what regex can do.

JavaScript - Regular Expressions

I have an HTML page with a text box. This text box has an id of "myTextBox". I am trying to use a regular expression in JavaScript to replace certain values in the text box with another value. Currently, I am trying the following
function replaceContent()
{
var tb = document.getElementById("myTextBox");
if (tb != null)
{
var current = new String(tb.value);
var pattern = new RegExp("(ft.)|(ft)|(foot)", "ig");
current = current.replace(pattern, "'");
alert(current);
}
}
Based on this code, if I had the value "2ft" in the myTextBox, I would expect the current variable to be "2'". However, it always shows an empty string. I fear there is something that I am misunderstanding in relation to regular expressions in JavaScript. What am I doing wrong?
Thank you!
Rewrite your pattern to:
(ft\.?|foot|feet)
This will match "ft" or "ft." and "foot" or "feet".
When writing code that uses regular expressions that won't behave, assume (first) that it is your regex that is the problem. Thanks to the compact and esoteric "programming" of regular expressions, it's quite easy to make a mistake you don't see.
If you test the following in Firebug to yield a correct result:
"2ft".replace(/(ft\.?|foot|feet)/ig, "'")
You will get "2'" in your console.
So this answer ought to solve your problem, if the regex is your problem in the first place. Like Rubens said, please check the ID of your textbox and ensure that the item is correctly retrieved.
As The Wicked Flea says, the literal '.' in your regex needs to be escaped. If it's in a character class it can be written un-escaped, but outside of one it must be escaped.
The following works for me:
<script>
var current = "2ft";
var pattern = new RegExp("(ft.)|(ft)|(foot)", "ig");
current = current.replace(pattern, "'");
alert(current);
</script>
Are you sure that tb.value is evaluating properly?
I ran your code using IE8,Chrome and FF3 with no problems.
Please check if your textbox id is correct.
The problem is that you're alternating explicit groupings. Instead you can just do something like the following:
function replaceContent()
{
var tb = document.getElementById("myTextBox");
if (tb != null) {
current = tb.value.replace(/\s*(ft\.|ft|foot|feet)\b/ig, "'");
alert(current);
}
}
Also, note the \s* which will strip leading spaces and the \b which marks the beginning/end of a word. I also added feet.

Categories