I want to find and replace text in a HTML document between, say inside the <title> tags. For example,
var str = "<html><head><title>Just a title</title></head><body>Do nothing</body></html>";
var newTitle = "Updated title information";
I tried using parseXML() in jQuery (example below), but it is not working:
var doc= $($.parseXML(str));
doc.find('title').text(newTitle);
str=doc.text();
Is there a different way to find and replace text inside HTML tags? Regex or may be using replaceWith() or something similar?
I did something similar in a question earlier today using regexes:
str = str.replace(/<title>[\s\S]*?<\/title>/, '<title>' + newTitle + '<\/title>');
That should find and replace it. [\s\S]*? means [any character including space and line breaks]any number of times, and the ? makes the asterisk "not greedy," so it will stop (more quickly) when it finds </title>.
You can also do something like this:
var doc = $($.parseXML(str));
doc.find('title').text(newTitle);
// get your new data back to a string
str = (new XMLSerializer()).serializeToString(doc[0]);
Here is a fiddle: http://jsfiddle.net/Z89dL/1/
This would be a wonderful time to use Javascript's stristr(haystack, needle, bool) method. First, you need to get the head of the document using $('head'), then get the contents using .innerHTML.
For the sake of the answer, let's store $('head').innerHTML in a var called head. First, let's get everything before the title with stristr(head, '<title>', true), and what's after the title with stristr(head, '</title>') and store them in vars called before and after, respectively. Now, the final line is simple:
head.innerHTML = before + "<title>" + newTitle + after;
Related
Okay, so I have a filepath with a variable prefix...
C:\Users\susan ivey\Documents\VKS Projects\secc-electron\src\views\main.jade
... now this path will be different for whatever computer I'm working on...
is there a way to traverse the string up to say 'secc-electron\', and drop it and everything before it while preserving the rest of it? I'm familiar with converting strings to arrays to manipulate elements contained within delimiters, but this is a problem that I have yet to come up with an answer to... would there be some sort of regex solution instead? I'm not that great with regex so I wouldn't know where to begin...
What you probably want is to do a split (with regex or not):
Here's an example:
var paragraph = 'C:\\Users\\susan ivey\\Documents\\VKS Projects\\secc-electron\\src\\views\\main.jade';
var splittedString = paragraph.split("secc-electron"); // returns an array of 2 element containing "C:\\Users\\susan ivey\\Documents\\VKS Projects\\" as the first element and "\\src\\views\\main.jade" as the 2nd element
console.log(splittedString[1]);
You can have a look at this https://www.w3schools.com/jsref/jsref_split.asp to learn more about this function.
With Regex you can do:
var myPath = 'C:\Users\susan ivey\Documents\VKS Projects\secc-electron\src\views\main.jade'
var relativePath = myPath.replace(/.*(?=secc-electron)/, '');
The Regex is:
.*(?=secc-electron)
It matches any characters up to 'secc-electron'. When calling replace it will return the last part of the path.
You can split the string at a certain point, then return the second part of the resulting array:
var string = "C:\Users\susan ivey\Documents\VKS Projects\secc-electron\src\views\main.jade"
console.log('string is: ', string)
var newArray = string.split("secc-electron")
console.log('newArray is: ', newArray)
console.log('newArray[1] is: ', newArray[1])
Alternatively you could use path.parse(path); https://nodejs.org/api/path.html#path_path_parse_path and retrieve the parts that you are interested in from the object that gets returned.
UPDATE: I am no longer specifically in need of the answer to this question - I was able to solve the (larger) problem I had in an entirely different way (see my comment). However, I'll check in occasionally, and if a viable answer arrives, I'll accept it. (It may take a week or three, though, as I'm only here sporadically.)
I have a string. It may or may not have HTML tags in it. So, it could be:
'This is my unspanned string'
or it could be:
'<span class="someclass">This is my spanned string</span>'
or:
'<span class="no-text"></span><span class="some-class"><span class="other-class">This is my spanned string</span></span>'
or:
'<span class="no-text"><span class="silly-example"></span></span><span class="some-class">This is my spanned string</span>'
I want to find the index of a substring, but only in the portion of the string that, if the string were turned into a DOM element, would be (a) TEXT node(s). In the example, only in the part of the string that has the plain text This is my string.
However, I need the location of the substring in the whole string, not only in the plain text portion.
So, if I'm searching for "span" in each of the strings above:
searching the first one will return 13 (0-based),
searching the second will skip the opening span tag in the string and return 35 for the string span in the word spanned
searching the third will skip the empty span tag and the openings of the two nested span tags, and return 91
searching the fourth will skip the nested span tags and the opening of the second span tag, and return 100
I don't want to remove any of the HTML tags, I just don't want them included in the search.
I'm aware that attempting to use regex is almost certainly a bad idea, probably even for simplistic strings as my code will be encountering, so please refrain from suggesting it.
I'm guessing I will need to use an HTML parser (something I've never done before). Is there one with which I can access the original parsed strings (or at least their lengths) for each node?
Might there be a simpler solution than that?
I did search around and wasn't been able to find anyone ask this particular question before, so if someone knows of something I missed, I apologize for faulty search skills.
The search could loop through the string char by char. If inside a tag, skip the tag, search the string only outside tags and remember partial match in case the text is matched partially then interrupted with another tag, continue the search outside the tag.
Here is a little function I came up with:
function customSearch(haysack,needle){
var start = 0;
var a = haysack.indexOf(needle,start);
var b = haysack.indexOf('<',start);
while(b < a && b != -1){
start = haysack.indexOf('>',b) + 1;
a = haysack.indexOf(needle,start);
b = haysack.indexOf('<',start);
}
return a;
}
It returns the results you expected based in your examples. Here is a JSFiddle where the results are logged in the console.
Let's start with your third example:
var desiredSubString = 'span';
var entireString = '<span class="no-text"></span><span class="some-class"><span class="other-class">This is my spanned string</span></span>';
Remove all HTML elements from entireString, above, to establish textString:
var textString = entireString.replace(/(data-([^"]+"[^"]+")/ig,"");
textString = textString.replace(/(<([^>]+)>)/ig,"");
You can then find the index of the start of the textString within the entireString:
var indexOfTextString = entireString.indexOf(textString);
Then you can find the index of the start of the substring you're looking for within the textString:
var indexOfSubStringWithinTextString = textString.indexOf(desiredSubString);
Finally you can add indexOfTextString and indexOfSubStringWithinTextString together:
var indexOfSubString = indexOfTextString + indexOfSubStringWithinTextString;
Putting it all together:
var entireString = '<span class="no-text"></span><span class="some-class"><span class="other-class">This is my spanned string</span></span>';
var desiredSubString = 'span';
var textString = entireString.replace(/(data-([^"]+"[^"]+")/ig,"");
textString = textString.replace(/(<([^>]+)>)/ig,"");
var indexOfTextString = entireString.indexOf(textString);
var indexOfSubStringWithinTextString = textString.indexOf(desiredSubString);
var indexOfSubString = indexOfTextString + indexOfSubStringWithinTextString;
You could use the browser's own HTML parser and XPath engine to search only inside the text nodes and do whatever processing you need.
Here's a partial solution:
var haystack = ' <span class="no-text"></span><span class="some-class"><span class="other-class">This is my spanned string</span></span>';
var needle = 'span';
var elt = document.createElement('elt');
elt.innerHTML = haystack;
var iter = document.evaluate('.//text()[contains(., "' + needle + '")]', elt).iterateNext();
if (iter) {
var position = iter.textContent.indexOf(needle);
var range = document.createRange();
range.setStart(iter, position);
range.setEnd(iter, position + needle.length);
// At this point, range points at the first occurence of `needle`
// in `haystack`. You can now delete it, replace it with something
// else, and so on, and after that, set your original string to the
// innerHTML of the document fragment representing the range.
console.log(range);
}
JSFiddle.
I want to find and replace text in a HTML document between, say inside the <title> tags. For example,
var str = "<html><head><title>Just a title</title></head><body>Do nothing</body></html>";
var newTitle = "Updated title information";
I tried using parseXML() in jQuery (example below), but it is not working:
var doc= $($.parseXML(str));
doc.find('title').text(newTitle);
str=doc.text();
Is there a different way to find and replace text inside HTML tags? Regex or may be using replaceWith() or something similar?
I did something similar in a question earlier today using regexes:
str = str.replace(/<title>[\s\S]*?<\/title>/, '<title>' + newTitle + '<\/title>');
That should find and replace it. [\s\S]*? means [any character including space and line breaks]any number of times, and the ? makes the asterisk "not greedy," so it will stop (more quickly) when it finds </title>.
You can also do something like this:
var doc = $($.parseXML(str));
doc.find('title').text(newTitle);
// get your new data back to a string
str = (new XMLSerializer()).serializeToString(doc[0]);
Here is a fiddle: http://jsfiddle.net/Z89dL/1/
This would be a wonderful time to use Javascript's stristr(haystack, needle, bool) method. First, you need to get the head of the document using $('head'), then get the contents using .innerHTML.
For the sake of the answer, let's store $('head').innerHTML in a var called head. First, let's get everything before the title with stristr(head, '<title>', true), and what's after the title with stristr(head, '</title>') and store them in vars called before and after, respectively. Now, the final line is simple:
head.innerHTML = before + "<title>" + newTitle + after;
I have a XML mark-up/code like the following. I want to replace the text inside one of the tags (in this case <begin>...</begin>) using JavaScript or jQuery.
<part>
<begin>A new beginning</begin>
<framework>Stuff here...</framework>
</part>
The source is inside a textarea. I have the following code, but it is obviously not doing what I want.
code=$("xml-code").val(); // content of XML source
newBegin = "The same old beginning"; // new text inside <begin> tags
newBegin = "<begin>"+newBegin +"</begin>";
code=code.replace("<begin>",newBegin); // replace content
This is just appending to the existing text inside the begin tags. I have a feeling this can be done only using Regex, but unfortunately I have no idea how to do it.
You can use the parseXML() jQuery function, then just replace the appropriate node with .find()/.text()
var s = "<part><begin>A new beginning</begin><framework>Stuff here...</framework></part>";
var xmlDoc = $($.parseXML(s));
xmlDoc.find('begin').text('New beginning');
alert(xmlDoc.text());
http://jsfiddle.net/x3aJc/
Similar to the other answer, using the $.parseXML() function, you could do this:
var xml = $.parseXML($("xml-code").val());
xml.find('begin').text('The same old beginning');
Note that there is no need to replace a whole node, just change it's text. Also, this works if there are multiple <begin> nodes that need the text as well.
You can user regular expression but better dont do it. Use DOM parsers.
var code = $('xml-code').html(); // content of XML source
var newBegin = "The same old beginning"; // new text inside <begin> tags
var regexp = new Regexp('(<part>)[^~]*(<\/part>)', i);
code = code.replace(regexp, '$1' + newBegin + '$2');
I have different sentences which all have double quotes in them, like:
<h3 class="myClass">Sentence one "ends like this"</h3>
<h3 class="myClass">Sentence two"ends like that"</h3>
<h3 class="myClass">Sentence three "another ending"</h3>
All on a page. Basically all values are differents, and I'm trying to have a line break just before the double quote so it would be like
<h3 class="myClass">Sentence one <br/>"ends like this"</h3>
<h3 class="myClass">Sentence two <br/>"ends like that"</h3>
<h3 class="myClass">Sentence three <br/>"another ending"</h3>
I'm kind of confused on which jQuery function should be used to be honest, between split, text ? Any help would be appreciated , I need to understand how to do this... Many thanks!
You can match the <h3> elements, then pass a function to html(). That function will be called for each element, will be passed the current element's inner HTML markup, and must return the new markup.
From there, you can use replace() to insert a <br /> element before the first double quote character:
$("h3.myClass").html(function(index, currentHtml) {
return currentHtml.replace('"', '<br />"');
});
You can test this solution in this fiddle.
Make a function that takes a jQuery object, gets its html, and changes it
function addBR($el) {
Get the element's html
var originalhtml = $el.html();
Split the html by the quotation mark, and join them with a new <br />
var newhtml = originalhtml.split('"').join('<br />"');
Apply the new html
$el.html(newhtml);
And that's it.
Call it with
addBR(jQuery element);
Example: http://jsfiddle.net/XFC5u/
I would take a look at the Javascript split() method but in essence you have the right idea. You want to split based on the double quote(\") and that will return you an array of all the splits where a double quote occurs.
So something like this would happen:
var array = $(".myClass").text().split("\"");
//array = [Sentence one, ends like this, ];
(Not 100% sure if code is right so someone please check ><)
and then from there you can kind of recreate the text with the included . At least that's the process of how I would go about it.
Also just remember that the split method does remove the \" from the array (because it uses it as a limiter to split them) so make sure to readd them when you are recreating the text.
As for if Jquery as a specific way of doing this, I'm not sure. If anyone would like to improve my answer, feel free.
Take a look here to see this code working:
$(".myClass").each(function() {
var text = $(this).text();
var q = text.indexOf('"');
$(this).html(text.substr(0, q) + "<br />" + text.substr(q));
});
just with some basic javascript (inside a jQuery loop offcourse)
$(".myClass").each(function() { // for each item of myClass
var text = $(this).text(); // temp store the content
var pos = text.indexOf('"'); // find the position of the "
$(this).html(text.slice(0,pos) + '</br>' + text.slice(pos)); // slice before + <br> + slice after = new content
});
fiddle:
http://jsfiddle.net/JaPdT/
$('.myClass').each(function(){
if($(this).text().indexOf('"') >=0 ){
$(this).text( $(this).text().replace('"', '<br/>"') )
}
})