1

I have a div element with the following html content:

<div id="status">
    Welcome, bob!
</div>

In my client side javascript file, I want to get the name bob in a variable:

var myName = document.getElementById("status").innerHTML;

Thus removing the first string Welcome, and the last character !, how can I achieve this?

2
  • 3
    You could just .slice, if its always going to be "Welcome, name!". Commented Jan 3, 2016 at 15:38
  • 3
    if you are generating this code yourself you could make things easier by adding the name to the div-tag and grab it from there. Like data-name=bob or something Commented Jan 3, 2016 at 15:40

2 Answers 2

4

Using .slice (simple, probably preferred, method):

If it is always going to be "Welcome, name!", you could use .slice:

var text = document.getElementById("status").innerHTML.trim();
var myName = text.slice(9, -1);

// myName === "bob"

This works with other names too.

<div id="status">
  Welcome, Jamen!
</div>

Would result in myName being "Jamen".


Using data-* attributes:

As RST elaborated, you could setup your HTML to make this a lot more simple, if it is yours.

<div id="status" data-name="Jamen">
  Welcome, Jamen!
</div>

With:

var myName = document.getElementById("status").getAttribute("data-name");

Using data-binding libraries:

As a big alternative, you could consider a library that does data-binding. For instance, here is an example using VueJS:

<div id="status">
  Welcome, {{name}}!
</div>

Then we can use:

var status = new Vue({
  el: '#status',
  data: { name: 'Jamen' }
});

// status.name === "Jamen" 

Of course, this is probably more than necessary for just this question, since data-binding libraries do a lot more than let you access values in HTML, but it's just a thought if you're doing more beyond what you posted in this question.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes the pattern will remain the same, thanks this works.
1

If you don't want to commit to Welcome you can define

function GetLastWordWithoutLastChar(text) {
    var words = text.split(" ");
    return words[words.length - 1].slice(0, -1);
}

and then use

var statusElement = document.getElementById("status");
var myName = GetLastWordWithoutLastChar(statusElement.innerHTML);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.