I have the following block
<span id="title"><select id="optionType"><option>choose option</option><option> hello</option><option>how are you</option></select></span>
I want to remove the first option and need to get the all other options in new line, only the option text with out any tags . Is regular expression is the best one to use, or is thire any other better method to retrieve text in new line ? I tried the following but it can fail somtimes
Description= $('title').innerHTML;
var tmp = Description;
tmp = tmp.replace("--Choose an option--</option>",""); // remove first option
tmp = tmp.replace(/<\/option><option>/g, "<\/option>\n<\/option>");
tmp = tmp.replace(/(<([^>]+)>)/g,"");
tmp = tmp.replace(/\n/g, "\n");
tmp = tmp.replace(/^[\s]*/gm, '');
return tmp;
Try with jQuery if possible instead of regex.
It would be something like
$("#optionType>option:first").remove() //to delete first option
$("#optionType>option") //list of other options
(<option[^>]*?>([^<]+)<\/option>)
Have you considered just removing the option directly rather than fiddling with the HTML code?
Particularly easy, since you're using JQuery already:
$("#title option[value='--Choose an option--']").remove();
See also: Removing an item from a select box
Related
I am trying to change the string displayed in the frontend by using a function in javascript.
let displayword = document.getElementById("displayword”)
console.log(displayword.innerText) //apple
Say, I want the change the letter “l” to something else say “i” but keep the rest of the letters unchanged how do I go around this?
Things I have tried
displayword.innerText[3] = “i” // -----does nothing----
I am confused why the above code using index does nothing, while the below does something
dash.innerText += “i” //applei
Extra question: Why does the above code using =+ change the formatting of the innerText? I want to keep the large font but it changes to regular font of the element (here I am using h1).
Thank you:)
You should look at the String documentation, especially String.slice and String.substring
In many languages, Strings can't be modified directly. Instead you "change" it by creating a new string composed of parts of the original.
As for how you'd do it in your case:
var text = displayWord.innerText;
text = text.slice(0, 3) + 'i' + text.slice(4) // apple -> appie
displayWord.innerText = text;
[Edited code slightly]
displayword.innerText = displayword.innerText.replace(oldCharacter, newCharacter);
To replace all occurrences:
displayword.innerText = displayword.innerText.replaceAll(oldCharacter, newCharacter);
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 have the following line in my jsp file:
var option = document.createElement('<option value="NO">');
Not sure why this gives me InvalidCharacterError.
Any alternatives?
You can use this code to add to your tag.
var myoption = document.createElement("option");
myoption.setAttribute("value", "carvalue");
var text = document.createTextNode("maruti");
myoption.appendChild(text);
document.getElementById("mySelect").appendChild(myoption);
There was a change in DOM implementation.
Before, you could create a new element with the code inside, for instance:
BAD
var anElement = document.createElement("StackOverflow")
This implementation now, returns this ‘InvalidCharacterError’.
What you must do now is to create the element and to populate it using the innerHTML attribute or the different specific attributes for any node.
GOOD
var anElement = document.createElement("a")
anElement.innerHTML = ("StackOverflow")
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 some lines of HTML code that are like this:
<li>Testing jQuery [First Bracket]</li>
<li>Loving jQuery [Second one]</li>
I'm trying to replace what's inside the bracket with nothing onLoad, like this:
var item = $(".lstItem").text();
var match = item.match(/\[(.*?)\]/);
item = item.replace(match[0], "");
But nothing changes. What's wrong and how to correct this?
After using jimbojw's suggestion I'm getting a Uncaught ReferenceError: text is not defined at this particular line:
oldtext = $item.text,
item is a variable containing a string, not a pointer to the literal text. If you want to change the text, you have to set it again, vis a vis $(".listItem").text(item)
edit - predicting next problem
The next problem you're going to have is that all the text gets set to the same thing. So what you really want to do is probably something like this:
$(".lstItem")
.each(function(index, item) {
var
$item = $(item),
oldtext = $item.text(),
match = oldtext.match(/\[(.*?)\]/),
newtext = oldtext.replace(match[0], '');
$item.text(newtext);
});
this will do the job for you:
you are splitting your code in too much lines, also your need to run replace for each individual element separately.
$(".lstItem").each(function() {
$(this).html(
$(this).html().replace(/\[(.*)\]/, "")
);
});
see your example in jsFiddle: http://jsfiddle.net/eKn3Q/7/
Along with jimbojw's answer $(".lstItem").text() will retrieve all the text inside of your <a/> elements. One way to handle this would be to pass a function(i,t){} into the .text() method.
$(".lstItem").text(function(i, text){
var match = text.match(/\[(.*?)\]/);
return text.replace(match[0], "");
});
Simple example on jsfiddle
also your regex could be simpler.
var item = $(".lstItem").text();
var match = /\[(.*?)\]/;
$(".listItem").text(item.replace(match,""));