Regular Expression is not working with string name - javascript

I have a Regular Expression in javascript that is not working. My code is...
JavaScript :
function doit()
{
var string="something";
var el=document.getElementById("monu");
el.innerHTML = el.innerHTML.replace(/(string)/ig,"Everything");
}
HTML :
<div id="monu">something is better than nothing</div>
<button onclick=doit();>replace</button>
In function replace if I am using string as pattern it is not working.
How can I make it work...any suggestion..

Use the RegExp constructor :
el.innerHTML = el.innerHTML.replace(new RegExp(string,'ig'),"Everything");
Note that if you want to replace a string containing special regex patterns without interpreting them as regex patterns (for example you want to replace exactly ".*"), then you need to escape your string. There's unfortunately no standard function in JavaScript for that but it's easy to write and find (here's one).

Related

Using search and replace with regex in javascript

I have a regular expression that I have been using in notepad++ for search&replace to manipulate some text, and I want to incorporate it into my javascript code. This is the regular expression:
Search
(?-s)(.{150,250}\.(\[\d+\])*)\h+ and replace with \1\r\n\x20\x20\x20
In essence creating new paragraphs for every 150-250 words and indenting them.
This is what I have tried in JavaScript. For a text area <textarea name="textarea1" id="textarea1"></textarea>in the HTML. I have the following JavaScript:
function rep1() {
var re1 = new RegExp('(?-s)(.{150,250}\.(\[\d+\])*)\h+');
var re2 = new RegExp('\1\r\n\x20\x20\x20');
var s = document.getElementById("textarea1").value;
s = string.replace(re1, re2);
document.getElementById("textarea1").value = s;
}
I have also tried placing the regular expressions directly as arguments for string.replace() but that doesn't work either. Any ideas what I'm doing wrong?
Several issues:
JavaScript does not support (?-s). You would need to add modifiers separately. However, this is the default setting in JavaScript, so you can just leave it out. If it was your intention to let . also match line breaks, then use [^] instead of . in JavaScript regexes.
JavaScript does not support \h -- the horizontal white space. Instead you could use [^\S\r\n].
When passing a string literal to new RegExp be aware that backslashes are escape characters for the string literal notation, so they will not end up in the regex. So either double them, or else use JavaScript's regex literal notation
In JavaScript replace will only replace the first occurrence unless you provided the g modifier to the regular expression.
The replacement (second argument to replace) should not be a regex. It should be a string, so don't apply new RegExp to it.
The backreferences in the replacement string should be of the $1 format. JavaScript does not support \1 there.
You reference string where you really want to reference s.
This should work:
function rep1() {
var re1 = /(.{150,250}\.(\[\d+\])*)[^\S\r\n]+/g;
var re2 = '$1\r\n\x20\x20\x20';
var s = document.getElementById("textarea1").value;
s = s.replace(re1, re2);
document.getElementById("textarea1").value = s;
}

replace in javascript with case conversion

I want to make the first character of every word in a string to uppercase.
i am referring to this article Replacement Text Case Conversion.
when i am running the regular expression ([a-zA-Z])([a-zA-Z](\s)) with the replacement text as \u$1\l$2 in my editor (sublime text) it works fine.
However, when i am trying to do the same in javascript using replace method as below, its giving syntax errors and hence fails.
var regex = /([a-zA-Z])([a-zA-Z]*(\s)*)/gi;
var rep = "\\u$1\\l$2"; // here it is giving error
var result = input.replace(regex,rep);
How to resolve this?
I know this problem can be solved using charAt() and toUppercase() method. but I want to do it using regex with replace. :)
JS regex engine does not support lower- and uppercasing operators \u and \l in the replacement patterns. Use a callback inside String#replace:
var input = "aZ";
var regex = /([a-zA-Z])([a-zA-Z]*(\s)*)/gi;
var result = input.replace(regex, function($0,$1,$2,$3) {
return $1.toUpperCase() + $2.toLowerCase();
});
console.log(result);
Note that you can reduce your pattern to /([a-z])([a-z]*\s*)/gi.

How to unescape JavaScript string literal value?

I am using regex to parse javascript code (using an ES parser, such as Esprima, is not an option for technical environment limitations).
The subject code (the code being parsed is):
(function() {
$('#3bf779cd').replaceWith("<div class=\'shows\'>\n<\/div>");
window.fadeItems();
}).call(this);
The value I am interested in is the first parameter of replaceWith, which is a string literal. I am getting this variable using regex:
const subjectValue = subjectCode.match(/\.replaceWith\(((["'])(?:(?=(\\?))\3.)*?\2)/m)[1].slice(1, -1);
console.log(subjectValue);
The output of this is:
<div class=\'shows\'>\n<\/div>
How do I escape subjectValue in a way that the output would be:
<div class='shows'>
</div>
Simply using unescape has no effect.
If I am not mistaken, the question comes does to how to unescape this value:
console.log('"<div class=\\\'shows\\\'>\\\\n<\\\/div>"');
You're looking for eval (yes you heard correctly):
text = document.querySelector('script').textContent;
dqString = /"(\\.|[^"])*"/g
s = text.match(dqString)[0]
raw = eval(s);
alert(raw);
<script>
(function() {
$('#3bf779cd').replaceWith("<div class=\'shows\'>\n<\/div>");
window.fadeItems();
});
</script>
The most idiotic way would be.
"<div class=\\'shows\\'>\\\\n<\\/div>".replace(/\\n/g, '').replace(/\\/g, '');
// "<div class='shows'></div>"
Smarter way would be to first unescape \n's than check with regex if there are unescaped matches, and than escape those as well.

split string of chain functions with reg-exp

I looked around on StackOverflow but could not find the answer!
Anyway, I was wondering how do I get following in JavaScript with regexp.
I have a string
bla().func1($(ele).attr("data")).func2.func3("test")... ;
and I want extract func1, func2, func3... from the given string, anybody have an example of how to do that?
Bear in mind, that the function names changes, so they are not func1, func2 ... they can be load, past, moon ... whatever
try this:
var str = 'bla().func1($(ele).attr("data")).func2("test")';
alert(str.split(/(?:\.)\w+\d+(?=\()/g));
There's the fiddle:
http://jsfiddle.net/cv6avhfb/3/
This code would split the string in parts while using as separators substrings like '.func1(', '.func2(', '.abc3(' and other. If the function names have different structure you just have to change the \w+\d+ part of the regex.
Here's the result of this code:
bla(),($(ele).attr("data")),("test")
And if you like to know more about regex in javascript:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
Repeatedly strip out innermost parenthesized expressions:
var str = 'bla().func1($(ele).attr("data")).func2.func3("test")... ';
var expression = /\([^(]*?\)/g;
while (expression.test(str)) { str = str.replace(expression, ''); }
document.write(str.split('.').slice(1).join(' '));
However, you shouldn't do this (why do you want to?). JS should be parsed by, well, JS parsers. For instance, the above will fail miserably if there's a string literal containing a parenthesis. You should parse this using Esprima and analyze the resulting parse tree.

JavaScript, Regex, var in pattern

right now, i have this replace:
var newcontent = newcontent
.replace(/<div id="container_gallery_"(.*)><\/div>/gi,"");
Is it possible to pass a variable in place of <div id="container_gallery_ ?
My
function delAlbum(a) { }
performs this replace, and I would like to put the variable a into the
-edit-
Thanks for the information provided!
Less hairloss!
You can build up the RegExp via the object notation and not the shorthand one:
function delAlbum(a) {
var regex = new RegExp( a + '"(.*)><\/div>', 'gi' );
var newcontent = newcontent
.replace( regex,"");
// ...
}
To put a variable into the regular expression, you need to construct the regular expression as a string and then pass it to the RegExp object constructor like this:
var target = a + "(.*)></div>";
var newcontent = newcontent.replace(new RegExp(target, "gi"), "");
In general, it is a bad idea to do regex matching on uncontrolled HTML and a really bad idea to do it on HTML that comes from the .innerHTML property because there are lots of legal HTML ways to break your regular expression.
As the other responders said, you can use a RegExp constructor for that. But while you're at it, you should get rid of that (.*). Assuming it's meant to consume whatever other attributes the <div> has, you'll be better off using [^<>]*. That will confine the match to one element at a time; (.*) is the ultimate escape artist.
But I'm curious: are you really passing in strings like <div id="container_gallery_", including the first part of the HTML element? Or are you only passing a replacement for the attribute's value, (e.g. container_gallery_)? If that's the case, this regex should serve you better:
var regex = new RegExp('<div\s+"` + (your var) + '"[^<>]*></div>', 'gi' );
I'm assuming the `id` attribute is always in the first position which generally not a safe assumption, but it makes the regex a lot easier, both to write and to read. ;)
And don't forget to check the passed-in string for characters that are illegal in an HTML attribute.

Categories

Resources