0

Having some issues getting my head around this. I am trying to use a function to split a variable into two and then add a html <span> tag around each character. I have managed to do this process through a variable easy enough however when I try as a function it does not work.

<script>
var value = "30";

function myFunction(a) {
    var a = a.split("", 2);
    var a = "<span>" + a[0] + "</span><span>" a[1] + "</span>";
}

document.getElementById("demo").innerHTML = myFunction(value);</script>

Any hints as to why this might be?

3 Answers 3

1
  • You have to return a value from the function
  • You missed one + in the "<span>" + a[0] + "</span><span>" a[1] + "</span>" line
  • If you want to split a word at every character, use empty quotation marks as the argument
  • You have used three a variables, overwriting each of them when declaring the new one

var value = "30";

function myFunction(a) {
    var b = a.split('');
    return "<span>" + a[0] + "</span><span>" + a[1] + "</span>";
}

document.getElementById("demo").innerHTML = myFunction(value);
<p id='demo'></p>

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

Comments

1

Since strings are arrays, you can do this:

var test = "1234";

function wrapSpans(a) {
    var tempStr = "";
    var x = 0;
    while(x < a.length) {
        tempStr += `<span>${a[x]}</span>`;
        x++;
    }
    return tempStr;
}

var value = "30";

document.querySelector("#demo").innerHTML = wrapSpans(test);
span {
  padding: 2px;
  background: yellow;
  margin: 2px;
}

div {
  padding: 2px;
  background: grey;
}
<div id="demo"></div>

Comments

0
  1. You are missing the + operator in the line
    var a = "<span>" + a[0] + "</span><span>" a[1] + "</span>";

    It should be

    var a = "<span>" + a[0] + "</span><span>" + a[1] + "</span>";

  2. You need to return a value from the function.

  3. No need to redefine the var a again and again.

var value = "30";

function myFunction(a) {
    var a = a.split("", 2);
    a = "<span>" + a[0] + "</span><span>" + a[1] + "</span>";
    return a;
}

document.getElementById("demo").innerHTML = myFunction(value);
<div id="demo"></div>

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.