I am trying to add a span to a specific word like this:
var value = "eror";
var template = "/(" + value + ")/g";
$("#content").html($("#content").html().replace(template, '<span class="spell_error">$1</span>'));
Here is my fiddle. I tried using a solution I saw here but it does not seem to work. ANy idea why?
Thank you
You're confusing regular expression literals and strings.
Use this to create your regex :
var template = new RegExp("(" + value + ")", 'g');
A regular expression literal is like this :
/(something)/
There's no quote. But as it is a literal, you can't build it with your code, so that's why you must use the RegExp constructor.
A side note : your replacement yould be made lighter and, more importantly, dryer by using the html variant taking a function as callback :
$("#content").html(function(_,html){
return html.replace(template, '<span class="spell_error">$1</span>')
});
Related
I have a Greasemonkey script that prints a div -- works! However, I'd like to be able to add bold tags to all dates in this div.
Dates are formatted MM/DD/YYYY
So something like:
var regex = '\d{2}\/\d{2}\/\d{4}';
Then how would I perform the search replace? If the div was called loanTable:
Non-working concept:
$("#loanTable").html().replace( regex, "<b>" regex "</b>" )
Something like the above should work but I'm not sure of the exact syntax for this.
Use a regex capture group:
var loanTable = $("#loanTable")
var loanHTML = loanTable.html ().replace (/(\d{2}\/\d{2}\/\d{4})/g, "<b>$1</b>");
loanTable.html (loanHTML);
This piece of code is not valid JS:
var regex = '\d{2}\/\d{2}\/\d{4}';
$("#loanTable").html().replace( regex, "<b>" regex "</b>" )
The syntax for regex is /regex/, non quoted, or new Regex('regex') with quotes.
Start by assigning the html to a variable. Also <b> is barely used anymore, <strong> is the new standard. Then, replace() takes a regex and a string or function as parameters. To replace multiple times you have to use the g flag. Finally, to do what you want to accomplish you can use replacement tokens, like $1 etc...
var re = /\d{2}\/\d{2}\/\d{4}/g; // 'g' flag for 'global';
var html = $("#loanTable").html();
$("#loanTable").html(html.replace(re, '<strong>$&</strong>')); // The `$&` token returns the whole match
Last time I used GreaseMonkey, it wasn't easy to get jQuery to run in your user scripts.
Use the following code to do it without jQuery:
var loanTable = document.getElementById('loanTable');
loanTable.innerHTML = loanTable.innerHTML.replace(/(\d{1,2}\/\d{1,2}\/\d{4})/g, "<b>$1</b>");
One small aspect of this: you need to concatenate strings with a + operator:
$("#loanTable").html().replace( regex, "<b>" + regex + "</b>" )
I am trying to create a regular expression that would easily replace an input name such as "holes[0][shots][0][unit]" to "holes[0][shots]1[unit]". I'm basically cloning a HTML input and would like to make sure its position is incremented.
I got my regex built and working correctly using this (awesome) tool : http://gskinner.com/RegExr/
Here is my current regex :
(.*\[shots\]\[)([0-9]+)(\].*\])
and I am using a replace such as :
$12$3
this transforms "holes[0][shots][0][unit]" into "holes[0][shots][2][unit]". This is exactly want I want. However, when I try this in javascript (http://jsfiddle.net/PH2Rh/) :
var str = "holes[0][shots][0][units]";
var reg =new RegExp("(.*\[shots\]\[)([0-9]+)(\].*\])", "g");
console.log(str.replace(reg,'$1'));
I get the following output : holes[0
I don't understand how my first group is supposed to represent "holes[0", since I included the whole [shots][ part in it.
I appreciate any inputs on this. THank you.
In strings, a single \ is not interpreted as a Regex-escaping character. To escape the bracket within string literals, you have to use two backslashes, \\:
var reg = new RegExp("(.*\\[shots\\]\\[)([0-9]+)(\\].*\\])", "g");
A preferable solution is to use RegEx literals:
var reg = /(.*\[shots\]\[)([0-9]+)(\].*\])/g;
Looks like, this works:
var str = "holes[0][shots][0][units]";
var reg = /(.*\[shots\]\[)([0-9]+)(\].*\])/;
console.log(str.replace(reg,'$1'));
I'm trying to take some parsed XML data, search it for instances of the tag and replace that tag (and anything that may be inside the font tag), and replace it with a simple tag.
This is how I've been doing my regexes:
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/; //Test against valid email
console.log('regex: ' + emailReg.test(testString));
and so I figured the font regex would be something like this:
var fontReg = /'<'+font+'[^><]*>|<.'+font+'[^><]*>','g'/;
console.log('regex: ' + fontReg.test(testString));
but that isn't working. Anyone know a way to do this? Or what I might be doing wrong in the code above?
I think namuol's answer will serve you better then any RegExp-based solution, but I also think the RegExp deserves some explanation.
JavaScript doesn't allow for interpolation of variable values in RegExp literals.
The quotations become literal character matches and the addition operators become 1-or-more quantifiers. So, your current regex becomes capable of matching these:
# left of the pipe `|`
'<'font'>
'<''''fontttt'>
# right of the pipe `|`
<#'font'>','g'
<#''''fontttttt'>','g'
But, it will not match these:
<font>
</font>
To inject a variable value into a RegExp, you'll need to use the constructor and string concat:
var fontReg = new RegExp('<' + font + '[^><]*>|<.' + font + '[^><]*>', 'g');
On the other hand, if you meant for literal font, then you just needed:
var fontReg = /<font[^><]*>|<.font[^><]*>/g;
Also, each of those can be shortened by using .?, allowing the halves to be combined:
var fontReg = new RegExp('<.?' + font + '[^><]*>', 'g');
var fontReg = /<.?font[^><]*>/g;
If I understand your problem correctly, this should replace all font tags with simple span tags using jQuery:
$('font').replaceWith(function () {
return $('<span>').append($(this).contents());
});
Here's a working fiddle: http://jsfiddle.net/RhLmk/2/
I have a working reg expression that does a replace function based on the expression. It works perfect. It finds a specific string based on the beginning of the string and the expression. This is it:
str.replace(/\bevent[0-9]*\=/, "event");
what this does is it changes event=1 to event.
What if event was a variable word? What if I needed to look for conference also?
I have tried:
var type = "conference";
str.replace(/\b/ + type+ /[0-9]*\=/, "conference");
and:
str.replace(/\b/type/[0-9]*\=/, "conference");
neither worked.
how can I pass a javascript string into a regular expression?
Instead of writing a RegEx literal, use a string to create a new RegExp object:
str.replace(new RegExp('\b' + var + '[0-9]'), …)
You can do that with the RegExp Object:
str.replace(RegExp('\b' + reStr + '[0-9]*\='),StrToReplaceWith)
Create a new regex object with your variable.
read this...
http://www.w3schools.com/js/js_obj_regexp.asp
I'm trying to use the replace function in JavaScript and have a question.
strNewDdlVolCannRegion = strNewDdlVolCannRegion.replace(/_existing_0/gi,
"_existing_" + "newCounter");
That works.
But I need to have the "0" be a variable.
I've tried:
_ + myVariable +/gi and also tried
_ + 'myVariable' + /gi
Could someone lend a hand with the syntax for this, please. Thank you.
Use a RegExpobject:
var x = "0";
strNewDdlVolCannRegion = strNewDdlVolCannRegion.replace(new RegExp("_existing_" + x, "gi"), "existing" + "newCounter");
You need to use a RegExp object. That'll let you use a string literal as the regex, which in turn will let you use variables.
Assuming you mean that you want the zero to be any single-digit number, this should work:
y = x.replace(/_existing_(?=[0-9])/gi, "existing" + "newCounter");
It looks like you're trying to actually build a regex literal with string concatenation - that won't work. You need to use the RegExp() constructor form instead, in order to inject a specific variable into the regex: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/RegExp
If you use the RegExp constructor, you can define your pattern using a string like this:
var myregexp = new RegExp(regexstring, "gims") //first param is pattern, 2nd is options
Since it's a string, you can do stuff like:
var myregexp = new RegExp("existing" + variableThatIsZero, "gims")