Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

For example our url: example.com

and source code is:

<html>
<head>
<body>
Hello My Name is: Jane
</body>
</head>
</html>

My question is: How we can get only "Jane" part using javascript?

share|improve this question
1  
With String.match or RegExp.exec. – raina77ow Jun 15 at 11:18
1  
That depends on the file structure. In your case the text would be in the body, so you'd get it with document.body.textContent but it's far better to give the parent element an id and look that up using document.getElementById(..) – Mr Lister Jun 15 at 11:18
By the way, after your edit, you now have an error in your HTML source... – Mr Lister Jun 19 at 13:50

1 Answer

up vote 1 down vote accepted

While looking at this page, pop up your browser's Javascript console and type:

$('body').text().match(/Hello My Name is: (\w+)/)

and you may see

["Hello My Name is: Jane", "Jane"]

You could assign the array to a variable and extract the second element.

One one line:

$('body').text().match(/Hello My Name is: (\w+)/)[1]
"Jane"

However, note that there can be horrific consequences of extracting things out of HTML with a regular expression and so it is considered a bad practice.

share|improve this answer
ok but i need get the source code from "url" – Erkan Berk Jun 15 at 11:34
If you want to fetch an external URL and parse it with javascript code, from the browser, is disallowed. There is a javascript security model called "single origin policy" that mostly disallows it. You can slurp in the whole thing in an iframe or frame if you want someone to see it, the framed content exists in its own container. There are workarounds to this security policy, but I don't think they apply to your use case. JSONP, for instance, requires special settings on the server. – Paul Jun 15 at 11:43

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.