简体   繁体   English

在javascript中使用regex和replace()替换数组元素

[英]Replacing array elements using regex and replace() in javascript

I'm bit new to JavaScript, I'm trying to replacing the array element using regex that matches the string, here is a code which I tried 我对JavaScript有点陌生,我正在尝试使用与字符串匹配的正则表达式替换数组元素,这是我尝试过的代码

<button onclick="myFunction()">ClickHere</button>
<p id="demo"></p>
<script>
function myFunction() {
    var abc = ["deno", "eno","pqr","lenovo"];
    var i,text;
    for(i = 0; i < abc.length; i++) {
        text += abc[i].replace(/no/i, "po");
        document.getElementById("demo").innerHTML = text;
    }
}
</script>

I want to replace array element with "po" wherever it encounters "no" in the array element string. 我想在数组元素字符串中遇到“否”的地方都用“ po”替换数组元素。

This is what I expect: 这是我期望的:

abc["depo","epo","pqr","lepovo"]

You can do this for every element: 您可以对每个元素执行此操作:

for(var i=0; i < abc.length; i++) {
    abc[i] = abc[i].replace('no', 'po');
}

or using one line 或使用一行

abc = abc.map(function(x){return x.replace('no', 'po');});

or using one line with "arrow functions": 或使用带有“箭头功能”的一行:

abc = abc.map(x => x.replace('no', 'po'));

After you changed the array, you can convert it to a string using: 更改数组后,可以使用以下命令将其转换为字符串:

var text = 'abc['; 

for ( var i = 0 ; i < abc.length ; i++ ) {
    text+='\"'+abc[i]+'\"';
    if ( i != abc.length - 1) {
        text+=',';
    }
}
text += ']';

Test: 测试:

 function myFunction() { var abc = ["deno", "eno","pqr","lenovo"]; abc = abc.map(x => x.replace('no', 'po')); // see other 2 alternatives above var text = 'abc['; for ( var i = 0 ; i < abc.length ; i++ ) { text+='\\"'+abc[i]+'\\"'; if ( i != abc.length - 1) { text+=','; } } text += ']'; document.getElementById("demo").innerHTML = text; } 
 <button onclick="myFunction()">ClickHere</button> <p id="demo"></p> 

var i, text;
for(i = 0; i < abc.length, i++) {
  text += abc[i].replace("no", "po");
}
  console.log(text);

There are three changes required in your code: 您的代码需要进行三处更改:

  1. Initialiize text with empty string.Because it is undefined by default. 使用空字符串初始化文本,因为默认情况下未定义。
  2. Change abc[i].length to abc.length. 将abc [i] .length更改为abc.length。
  3. Replace comma with a semicolon after abc[i].length in for loop. 在for循环中的abc [i] .length之后,用分号替换逗号。

     var abc = ["deno", "eno","pqr","lenovo"]; var i; var text = ""; for(i = 0; i < abc.length; i++) { text += abc[i].replace("no", "po"); } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM