javascript string.lastIndexOf does not work with span innerHTML - javascript

look the below example.
<html>
<body>
<form>
<span id="spTest">Your current operation: Modify » newone</span>
</form>
<script type="text/javascript">
var sp = document.getElementById("spTest");
var str = sp.innerHTML;
//var str = "Your current operation: Modify » newone";
alert(str)
var index = str.lastIndexOf("»");
alert(index);
</script>
</body>
</html>
the above example will popup the "index" value -1. If I uncomment the line ""Your current operation: Modify » newone";", the result will be 30.
So I think the reason is because I use the "innerHTML" to get the text. What else can i use the get text inside span and get the right index result?
Thanks

No, it has nothing to do with innerHTML. In the call to lastIndexOf, the » entity is not expanded as it is in the HTML code; instead it is considered as a raw string. Replace it with the actual character and it will work:
var index = str.lastIndexOf("»");

If you use innerHTML, you have to use "»" instead of "»".

Related

How to get a spicific tag data from .html() returned value

I have this HTML which i get it from $('#article').html() ,
i don't really know how to accomplish this with split() function :
<sometag1>some data1</sometag1>
<sometag2>some data2</sometag2>
<sometag13>some data3</sometag13>
so how i can split it and get the result such like:
result=>some data1
i tried this:
data1=$('#article').html().split('</sometag1>');
data1=$('#article').html().split('</sometag1>')[1].split('</sometag2>');
data1=$('#article').html().split('</sometag1>')[1].split('</sometag2>')[1].split('</sometag3>');
but that didn't really work ,and i think that not a very good code either:
so any idea how to do that?
EDIT:
After you changed your question, this is what you want: (demo below)
data1 = $('#article').html().split("<sometag1>")[1].split("</sometag1>")[0]
Do it like this: $('#article').find('sometag1').text()
First you get the parent element: $('#article')
Then you find it's subelement: find('sometag1')
And Finaly you get it's text content: .text()
Demo:
var data1 = $('#article').find('sometag1').text()
// What you want after edeting the question:
var data1 = $('#article').html().split("<sometag1>")[1].split("</sometag1>")[0]
console.log(data1)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="article">
<sometag1>some data1</sometag1>
<sometag2>some data2</sometag2>
<sometag13>some data3</sometag13>
</div>
Jquery:
data1=$("#article > sometag1");
data2=$("#article > sometag2");
data3=$("#article > sometag2");
/*if you want to get html inside tags then
then add .html() to each of lines up */
Javascript Solution
You can achieve that using getElementsByTagName("tagName"), e.g :
document.getElementsByTagName("sometag1")[0].textContent; //return some data1
Or using querySelector :
document.querySelector('sometag1').innerText; //return some data1
Or querySelectorAll :
document.querySelectorAll('sometag1')[0].firstChild.innerText; //return some data1
Hope this helps.
I too tried something try it.
my code goes like this
var data1=$('#article');
console.log(data1);
var i=0;
var a={};
a[i++]=data1.find('sometag1').text();
a[i++]=data1.find('sometag1').text();
//can do it for any other <sometag> as well
console.log(a);
result set was something like this
Object {0: "some data1", 1: "some data2"}
Working snippet to grub desired data below.
var result = [];
$('#article > *').each(function(){result.push($( this ).text())})
console.log(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="article">
<sometag1>some data1</sometag1>
<sometag2>some data2</sometag2>
<sometag13>some data3</sometag13>
</div>
Good luck!

How to get Html Element's Text

I want to extract the text part of the html.
If I have <p>ABCD</p>
I want the out put to be ABCD
Something like,
var html='<p>ABCD</p>';
var str = convertToString(html);
Hope, I will need a function which converts from html to string, or maybe extract string from it.
You can use jQuery to extract the text content from the string
var html = '<p>ABCD</p>';
var str = $(html).text();//get a jQuery reference and then read its text content
console.log(str)
All you need is a selector(id,class name etc) of get the required element of DOM and use .text() to get text part of the html.
HTML
<p>ABCD</p>
Jquery
var str = $('p').text(); // $('p') "p" is a selector to select p element(s)
console.log(str)
DEMO
JavaScript way
var txt = document.getElementById("demo").innerHTML;
alert(txt);
<p id="demo">Test text</p>
var html = '<p>ABCD</p>';
var str = $(html).text();
console.log(str);
This would do the task.

How can i get my string replace with to equal the value of a form input?

Im trying to use string replace to change a line of code within my page.
<script type="text/javascript">
function replaceScript() {
var toReplace = 'LINE OF CODE 333';
var replaceWith ='??????????';
document.body.innerHTML = document.body.innerHTML.replace(toReplace, replaceWith);
}
</script>
How can I get my...
var replaceWith ='??????????';
...to equal the value of an input from a form on the page?
Note the input value is auto populated on page load and the user does not enter in there own email address.
I assume you have an input such as <input id="inputValue" type="text" />
The general approach is to use a DOM function like getElementById() or querySelector(), and access its value with the value property.
Your code could be as simple as:
<script type="text/javascript">
function replaceScript() {
var toReplace = 'LINE OF CODE 333';
var replaceWith = document.getElementById('inputValue').value;
document.body.innerHTML = document.body.innerHTML.replace(toReplace, replaceWith);
}
</script>

javascript to replace all instances of a text within [] with hyperlinks

Am now facing an other challenge. Some parts of my html code has the following lines:
<div class="action-body flooded"><p>(In <span class="error">[82681]</span>) refs AGLBD-16096<br/></div>
I have to get the number with-in the [] and then replace it with a hyperlink. I have tried using document.getElementsByClassName('error') but its not working. how can I make it work? and i would also need to iterate in a loop to replace all such numbers if there are more than one in []. e.g: [123] [234] [345]...
This is all what I have written till now with pimvdb's help:
<script type="text/javascript">
var bodyText = document.getElementById('body').innerHTML;
var pattern = /\[.*?\]/g;
var replaceText = "Pradeep";
document.getElementById('body').innerHTML = bodyText.replace(pattern, replaceText);
</script>
This JSFiddle does what you need: http://jsfiddle.net/TNyms/
When you replace getElementById('body') with document.body, the code works for me.
var body = document.body;
var link = "Pradeep";
body.innerHTML = body.innerHTML.replace(/\[.*?\]/g, link);
That replaces all IDs in this with links:
<div class="action-body flooded">
<p>(In
<span class="error">[82681]</span>) refs
AGLBD-16096
<br/>
</div>
<div>[123][abcd]</div>
<div>[456]</div>
<div>[789]</div>
Outputs:
(In Pradeep) refs AGLBD-16096
PradeepPradeep
Pradeep
Pradeep
Try it with this fiddle.
Your question appears to be related to what is asked in the below link. You may refer this
Replace number in a string using regex or something else

Replace the contents of a div with regex match of string

I'm trying to figure out how to replace the contents of a <div> with the results from a regex .match() statement on a string. This is the code I have so far but I can't get it to work. I want the button to stay on screen but the <div> to reflect the matched word.
<html>
<body>
<script type="text/javascript">
function search(){
var str = "Visit W3Schools";
var patt1 = /w3schools/i;
document.write(str.replace(document.getElementById("results"),
(str.match(patt1))));
}
</script>
</body>
<div id="results">So this is some text.</div>
<button name="Search" onclick="search()">Click Here</button>
</html>
Any ideas as to why it's not working?
You need to stop the button completing it's default event, which is to submit the page. (Edit: No it's not, its default event is nothing - assumed it was a <submit> :) )
In addition, to get a div from the document basic on it's id attribute, you use document.getElementById('id-of-element') and to set the contents of a div, you use .innerHTML on the element we just got.
// We need to take the event handler as a parameter for the function, let's call it e
function search(e){
var str = "Visit W3Schools";
var patt1 = /w3schools/i;
document.getElementById("results").innerHTML = str.match(patt1)[0];
// This line stops the default action occurring
e.preventDefault();
}
Note: we don't need to specify an argument here, e goes in automatically
<button name="Search" onclick="search()">Click Here</button>
Your code is searching for the String "So this is come text." in the String "Visit W3Schools" and replacing it with the array ["W3Schools"], then writing it to the screen. This doesn't make much sense.
Try something like this instead:
function search(){
var str = "Visit W3Schools";
var patt1=/w3schools/i;
document.getElementById("results").innerHTML=(str.match(patt1))[0];
}
document.write will replace the entire page with the passed in parameter. So you just want to update that single DIV, results. So you want to use innerHTML:
function search() {
var str = "Visit W3Schools";
var patt1 = /w3schools/i;
document.getElementById("results").innerHTML = str.match(patt1)[0];
}

Categories

Resources