-2

How can I get some part of the HTML body with JavaScript;

Eq:

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

How can I get and assign a variable, only the "Jane" part using JavaScript?

  • 1
    With [String.match](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match) or [RegExp.exec](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec). – raina77ow Jun 15 '13 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 '13 at 11:18
  • By the way, after your edit, you now have an error in your HTML source... – Mr Lister Jun 19 '13 at 13:50

1 Answers1

1

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.

Community
  • 1
  • 1
Paul
  • 26,170
  • 12
  • 85
  • 119
  • 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 '13 at 11:43