var text_source="<a href='c:/exam_file.xls' target='_blank'>file downdload</a>";
text_search="file";
text_source.replace(new RegExp(text_search, 'gi'),
"<span style='font-weight:bold'>" +
text.toLowerCase() + "</span>");
The "a tag" link address has also changed:
<span style='font-weight:bold'>file</span> download
But, It should look like this. I have to change the text value in the "a tag".
<span style='font-weight:bold'>file</span> download
I will address what I said in a second, but you can do this without a loop with just pure regex. Below is how I accomplished this:
var text_source = "<a href='c:/bilmem_ne_dosyasi.xls' target='_blank'>Dosya Downdload</a>";
text_search = "dosya";
var patt = new RegExp("(<a .*?>)(" + text_search + ")(.*?</a>)","gi");
var text_source = text_source.replace(patt, function(match, $1, $2, $3) {
return $1 + "<span style='font-weight:bold'>" + $2.toLowerCase() + "</span>" + $3;
});
document.write(text_source);
DEMO
Getting back to what I said earlier, however, html can be a very, very complex language, and although regex can be used to parse it, partially, it should not be used for large quantities of data. Some patterns are too intricate to match against.
To ensure that your RegExp runs only against the content of the elements, you will need to select all of the elements that you want to manipulate and check their contents.
As an example:
var regExp = /dosya/ig;
[].slice.call(document.getElementsByTagName('a'), 0).forEach(function(element) {
if(regExp.test(element.textContent)) {
element.innerHTML = element.textContent.replace(regExp, function(text) {
return '<span style="font-weight: bold">' + text.toLowerCase() + '</span>';
})
}
});
There is also a jQuery pseudo selector :contains that does a similar thing.
Whilst the replies about not using regexes with HTML or XML are on the whole, correct, you could use the following for simple cases where you don't have too many nested tags:
var text_source="<a href='c:/bilmem_ne_dosyasi.xls' target='_blank'>Dosya Downdload</a>";
text_search="(<[^>]*>[^<]*)(dosya)([^<]*<[^>]*>)";
var replaced = text_source.replace(new RegExp(text_search, 'gi'), "$1<span style='font-weight:bold'>$2</span>$3");
Related
So I have this code that I am trying to alter –
Original:
jQuery(document).ready(function() {
var name = '';
var firstLastName = '[[T6:[[E48:[[S334:fr-id]]-[[S334:px]]:cons.first_name]]]] [[T6:[[E48:[[S334:fr-id]]-[[S334:px]]:cons.last_name]]]]';
var screenname = '[[T6:[[S48:0:screenname]]]]';
if (screenname) {
name = screenname;
} else {
name = firstLastName;
}
var splitName = name.split('');
var nameCheck = splitName[splitName.length-1];
jQuery('#personal_page_header h2').html("Support " + name + "'s Fundraiser" );
});
someone wrote this up and are no longer here, and what I'm trying to do now is figure out how to instead of replace the existing text, add to it.
So right now what this code does is it replaces the h2 content with the constituents registered name, or screenname.
What I'm trying to do now is append to that so that it will say something like
<h2>
Welcome to my fundraiser
<br/>
"Support" + name + "'s Fundraiser"
</h2>
but unfortunately what I tried breaks the code and stops it from working.
what I tried to do is this:
jQuery('#personal_page_header h2').append('<span><br />"Support " + name + "'s Fundraiser"</span>' );
I've tried to do a variety of other things that gave the same unsuccessful result.
Any help would be really appreciated!
Thanks
This should work for you:
jQuery('#personal_page_header h2').append("<span><br/>Support " + name + "'s Fundraiser</span>");
You've just got your quotations a little out of place.
You need to concatenate your code correctly, so if you'd like to keep the " use ' to concatenate. Further you need to escape the ' inside the string with \:
jQuery('#personal_page_header h2')
.append('<span><br />"Support ' + name + '\'s Fundraiser"</span>');
Looking for help with a javascript reg ex replacement. What I need, is to replace all instances of
width="100">
With
style="width: 100px;"
But the actual px value is variable which is what is causing issues for me. I know reg expression is the way to go but I dont quite understand it.
This is a similar question but doesn't solve the issue for me:
JavaScript Regex Replace Width Attribute Matching
The reason this is a problem is because of the HTML generated by TinyMce...
Two options:
Using a regular expression
Parsing the HTML and working with the DOM (preferred)
Using a regular expression
The expression is fairly straightforward:
str = str.replace(/\bwidth="(\d+)"/g, 'style="width: $1px"');
The $1 in the replacement string is filled in with the content of the first capture group.
Example:
var str = '<div width="100">Stuff here</div><div width="240">More stuff here</div>';
display("Before: '" + str + "'");
str = str.replace(/\bwidth="(\d+)"/g, 'style="width: $1px"');
display("After: '" + str + "'");
function display(msg) {
document.body.insertAdjacentHTML(
"beforeend",
"<p>" +
String(msg)
.replace(/&/g, "&")
.replace(/</g, "<") +
"</p>"
);
}
But note that that will:
Replace width="nnn" everywhere in the string, even if not inside a start tag
End up adding a second style attribute to a tag that already has one
If that's okay, great; if not, you might want to parse the HTML, process the resulting parsed DOM nodes, and then serialize it again.
Parsing the HTML and working with the DOM
A better option is to parse the HTML and work with the DOM. You've said that the HTML will be for a div, so we don't have to worry about things like standalone table cells, etc.
Here's a simple parsing and updating example:
var str = '<div width="100">Stuff here</div><div width="240">More stuff here</div>';
var div = document.createElement('div');
div.innerHTML = str;
update(div.childNodes);
display("Before: '" + str + "'");
str = div.innerHTML;
display("After: '" + str + "'");
function update(nodes) {
Array.prototype.forEach.call(nodes, function(node) {
var width;
if (node.nodeType === 1) { // An element
width = node.getAttribute("width");
if (width) {
node.removeAttribute("width");
node.style.width = width + "px";
}
update(node.childNodes);
}
});
}
function display(msg) {
document.body.insertAdjacentHTML(
"beforeend",
"<p>" +
String(msg)
.replace(/&/g, "&")
.replace(/</g, "<") +
"</p>"
);
}
My first thought also was to work with the DOM instead of using RegEx. Instead of iterating over all the elements, we could just use querySelector, which supports attribute selectors.
var html = '<img src="//placehold.it/100x100" alt="" style="100px;">'+
'<img src="//placehold.it/120x120" alt="" width="120" style="border: 2px solid steelblue;">'+
'<img src="//placehold.it/140x140" alt="" width="140">',
wrap = document.createElement('div'),
nodes;
wrap.innerHTML = html;
nodes = wrap.querySelectorAll('[width]');
Array.prototype.forEach.call(nodes, function(el) {
var width = el.getAttribute('width');
if(width) {
el.removeAttribute('width');
el.style.width = width+'px';
}
});
I'd like to build a string based on values defined in an html form only if they have been populated. I've successfully parsed the form fields and dropdown with a for loop ($.each()) but my ultimate goal is to dynamically build a string with the results. The string is being used to create a REST query, this is currently the only way to search based on our technologies. Does anyone have a recommended solution?
thx in advance
sample html element:
<input data-param=" prefix like '%" data-name="prefix" class="prefix uno" type="text" placeholder="pre">
working btn click event loop to capture filled in form fields:
var children = $(this).parent().children('.uno');
$.each(children, function(i, val){
if($(val).val() !== ''){
console.log($(val).data('name') + " "+ $(val).data('param') + " " + $(val).val());
}
});
goal:
var newString = field1.param + field1.val + '% ' + field2.param + field2.val + '% ';
translated:
var newString = prefix like '%01%' and name like '%tree%';
Thanks David Fregoli for the jquery serialize reference, that was close, but the solution ended up being to place the strings into a single array, change it toString(), and remove the ',' from the new string.
code:
var samp = [],
thisVal = $(this).parent().children('.uno');
$.each(thisVal, function(i, val){
if($(val).val() !== ''){
samp.push(
$(val).data('param'),
$(val).val(),
$(val).data('close')
);
}
});
itQuery.where = samp.toString().replace( /,/g , '');
result search string:
"number like '%08%' and field = 34"
I am using jQuery DatePicker to select elements with '#', everything is working fine when i put "direct" string in the selector, but once i begin concatenating, the result is very suspicious.
Maybe this console screenshot explain what i am struggling with
HTML :
<input id="wizard:wizard-body:datePiece_picker" name="wizard:wizard-body:datePiece_picker" type="text" value="">
Javascript :
function replaceAll(str, find, replace) {
return str.replace(new RegExp(find, "g"), replace);
}
var TYPEDIALOG = "wizard:wizard-body:";
var id = replaceAll(TYPEDIALOG, ":", "\\\\:")+ "datePiece_picker";
if ($("#" + id).length != 0) {
$("#" + id).datepicker({
dateFormat : "dd/mm/yy"
});
}
Your replace was adding too many backslashes:
http://jsfiddle.net/BaypN/
var id = replaceAll(TYPEDIALOG, ":", "\\:") + "datePiece_picker";
As a side note, this is probably a pretty good argument for avoiding : in element ids. Also, datePiece_picker could be a class instead of part of the id.
If I have a block of text inside a div like:
<div id='t1'>
This is a great testing string. Tomorrow grass is green.
</div>
and I want to replace all instance of the letter "g" with a link to google, like
<a href='www.google.com'>g</a>
Is it possible to do this with just Javascript/jquery?
If you want to perform a simple string replacement, the following will do:
var div = document.getElementById("t1");
div.innerHTML = div.innerHTML.replace(/g/g, "<a href='http://www.google.com'>g</a>");
If you need more dynamics, e.g. substituting a word with a link, depending on the value, use:
Example: Replace g or G with different URLs:
var div = document.getElementById("t1");
var mapper = {
g: "http://www.google.com",
G: "http://stackoverflow.com"
};
div.innerHTML = div.innerHTML.replace(/[Gg]/g, function(fullmatch){
return "<a href='" + mapper[fullmatch] + "'>" + fullmatch + "</a>";
});
No jQuery required.
var t1 = document.getElementById('t1')
t1.innerHTML = t1.innerHTML.replace(/g/g, 'g')
In /g/g, the first g is what you are searching for. The second g means global (aka replace all)
$('#t1').html( $('#t1').text().replace(/g/g,"<a href='www.google.com'>g</a>") );