0

Hey everyone I have one problem. I am trying to concatenate a single value from array with the string but it is not concatenating.

Example

arr[] => ['R','b','c']
string => "am"

I want to arr[0] + string i.e.., concatenate first index value of array to string.

How can I do this without changing the data type of array or string just concatenate array to string.

Edit: Here is the code

function rotate() {
  var string = document.getElementById("string").value

  var str_arr = string.split();

  document.getElementById("string").value = str_arr[string.length - 1] + string.substring(0, string.length - 1);
}
<fieldset>
  <label for="name">String:</label>
  <input type="text" id="string" name="string">
</fieldset>
<button type="submit" onclick="rotate()">Rotate</button>

7
  • May you edit the question with the javascript where you are concatenating? --- Also how can you concatenate ['R','b','c'] to 'am'?? Commented May 12, 2017 at 10:55
  • If i understand correct 'I am trying to concatenate a single value from array with the string ' you should do sometjing like arr[0] + 'am' => 'Ram' Commented May 12, 2017 at 10:58
  • 2
    string = arr[0] + string; ? Commented May 12, 2017 at 10:58
  • @evolutionxbox Please check the updated code. Commented May 12, 2017 at 11:02
  • Don't get it. You just want a string on input to duplicate at beginning the first character? Commented May 12, 2017 at 11:06

2 Answers 2

1

To reverse a string split it into array, rotate array and join it back to a string.

function check(){
  var string = document.getElementById("string").value;
  document.getElementById("string").value = string.split('').reverse().join('');
}
<fieldset>
      <label for="name">String:</label>
      <input type="text" id="string" name="string">
</fieldset>
<button type="submit" onclick="check()">Rotate</button>

To move last character in beginning of a string use substrings:

function check(){
  var string = document.getElementById("string").value;
  
  document.getElementById("string").value = string.substr(string.length - 1) + string.substr(0, string.length - 1);
}
<fieldset>
      <label for="name">String:</label>
      <input type="text" id="string" name="string">
</fieldset>
<button type="submit" onclick="check()">Rotate</button>

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

Comments

0

You can achive this using charAt() function.

function rotate(){

var string = document.getElementById("string").value var str_arr = string.split(); document.getElementById("string").value = string.charAt(string.length - 1) + string.substring(0, string.length - 1);

}

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.