最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I iterate over the characters in a string, and change them? - Stack Overflow

programmeradmin6浏览0评论

I want to take a string, and change each character. I.e. A bees E or F bees C.

what I have is this:

function convert(){
  var text=document.getElementById('textInp').value;
  alert(text);
  for()
}

I don't know what to do in the for loop

I want to take a string, and change each character. I.e. A bees E or F bees C.

what I have is this:

function convert(){
  var text=document.getElementById('textInp').value;
  alert(text);
  for()
}

I don't know what to do in the for loop

Share Improve this question asked May 19, 2017 at 10:13 G. LangG. Lang 511 gold badge1 silver badge4 bronze badges 1
  • Strings are immutable in JS, so you can only create a new string. // How to get the character at a certain position is something you can research yourself. And then, in your loop you either append the original character or the replacement to your new string. – C3roe Commented May 19, 2017 at 10:16
Add a ment  | 

5 Answers 5

Reset to default 4

You can iterate over each of the characters in the text like this

for (var x = 0; x < text.length; x++)
{
    var c = text.charAt(x);
    //Add code here to do the translation
}

You can split and join your String

function convert(){
   var text = document.getElementById('textInp').value;
   alert(text);
   text = text.split('A').join('E').split("F").join("C");
}

Try this split("") split the string with space .and match the letter then replace using map

function convert(){
  var text=document.getElementById('textInp').value;
 console.log(text.split("").map(a=> a= a.toUpperCase() == 'A'? 'E':a.toUpperCase() == 'F'?'C':a ).join(""))
}
<input id="textInp" value="AonFncdcd">
<button onclick="convert()">click</button>

There is a direct option to iterate over a string directly: to use for...of or for...in:

function convert(){
  let text = document.getElementById('textInp').value;
  for(let i in text) {
    // Do something
    console.info('i:', i, ' char: ', text[i])
  }
}
<input id="textInp" value="Your input">
<button onclick="convert()">click</button>

use string length and iterate and replace whatever you want.

for(var i=0 ; i < yourstring.length ; i++){
    yourstring= yourstring.replace(yourstring[i],"yourvalue")
}
发布评论

评论列表(0)

  1. 暂无评论