Pim
Pim

Reputation: 148

How to get a name out of a String in javascript

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?

Upvotes: 1

Views: 151

Answers (2)

guysigner
guysigner

Reputation: 2922

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);

Upvotes: 1

user3117575
user3117575

Reputation:

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.

Upvotes: 4

Related Questions