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

javascript string replace with all occurence with array value - Stack Overflow

programmeradmin1浏览0评论

I want to replace all occurrences of a string but the issue is that I have an array of remove words & remove words value.

for example :

var string = "this is a string to replace. This string should be replaced using javascript";

var replaceArray = ["this","is","string","should","javascript"];

var replaceArrayValue = ["There","are","strings","have to","node.js"];

for (var i = replaceArray.length - 1; i >= 0; i--) {

    var finalAns = string.replace(replaceArray[i],replaceArrayValue[i]);
}

I am expecting something like

There are strings to replace. There strings have to be replaced using node.js

I found some solutions in which I got the best solution here. but I can't use the string in /string/g. I have to use replaceArray[i]

I want to replace all occurrences of a string but the issue is that I have an array of remove words & remove words value.

for example :

var string = "this is a string to replace. This string should be replaced using javascript";

var replaceArray = ["this","is","string","should","javascript"];

var replaceArrayValue = ["There","are","strings","have to","node.js"];

for (var i = replaceArray.length - 1; i >= 0; i--) {

    var finalAns = string.replace(replaceArray[i],replaceArrayValue[i]);
}

I am expecting something like

There are strings to replace. There strings have to be replaced using node.js

I found some solutions in which I got the best solution here. but I can't use the string in /string/g. I have to use replaceArray[i]

Share Improve this question edited May 23, 2017 at 12:06 CommunityBot 11 silver badge asked Nov 7, 2016 at 8:59 chirag lathiyachirag lathiya 892 gold badges3 silver badges11 bronze badges 1
  • You can. var regex = new RegExp(replaceArray[i], 'g') – Rajesh Commented Nov 7, 2016 at 9:04
Add a comment  | 

5 Answers 5

Reset to default 5

If you prefer fixing your approach, you may use a RegExp constructor to build dynamic regexps with variables, and make sure you only match whole words enclosing the pattern with word boundaries. Do not forget to escape the literal patterns, and declare finalAns before the loop and initialize with the string var contents.

var string = "this is string to replace. this string should replace using javascript";
var replaceArray = ["this","is","string","should","javascript"];
var replaceArrayValue = ["There","are","strings","have to","node.js"];
var finalAns = string;
for (var i = replaceArray.length - 1; i >= 0; i--) {
    finalAns = finalAns.replace(RegExp("\\b" + replaceArray[i].replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') + "\\b", "g"), replaceArrayValue[i]);
}
console.log(finalAns);

Note that Roman's approach using a single static regex seems to be the most efficient for the current task (no need to build regexps dynamically each time).

Use the following approach with replacement function:

var string = "this is string to replace. this string should replace using javascript",
    replaced = string.replace(/\b\w+\b/g, function ($m) {
        var search = ["this","is","string","should","javascript"],
            replacement = ["There","are","strings","have to","node.js"],
            key = search.indexOf($m);

        return (key !== -1)? replacement[key] : $m;
    });

console.log(replaced);

From "High Performance JavaScript" (by Nicholas Zakas):

"... regarding out-of-scope variables: store any frequently used out-of-scope variables in local variables, and then access the local variables directly."

without Regular Exp

Only can set variable string =finalAns; in loop . Because Every time Loop set old string then issue are occurs ,

var string = "this is string to replace. this string should replace using javascript";

var replaceArray = ["this","is","string","should","javascript"];

var replaceArrayValue = ["There","are","strings","have to","node.js"];
alert(replaceArray.length);
for (var i = replaceArray.length - 1 ; i >= 0; i--) {

    var finalAns = string.replace(replaceArray[i],replaceArrayValue[i]);
    string =finalAns;
}
alert(finalAns);

Snippet Exmaple

var string = "this is string to replace. this string should replace using javascript";

var replaceArray = ["this","is","string","should","javascript"];

var replaceArrayValue = ["There","are","strings","have to","node.js"];

for (var i = replaceArray.length - 1 ; i >= 0; i--) {

    var finalAns = string.replace(replaceArray[i],replaceArrayValue[i]);
    string =finalAns;
}
alert(finalAns);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

I arrived to a solution using a declarative approach:

const string = 'boo and Boo2'
const dictionary = { boo: 'faa', boo2: 'faa2' }
return string.split(' ')
  .map(word => dictionary[word.toLowerCase()] ?? word)
  .join(' ')
// 'faa and faa2'

format method is for replacing all occurrences with order of the given array.

formatAll method is for replacing all first occurred words with order of the given array (which is asked for in the question)

String.prototype.format = function (_key, _data) {
  return this.split(_key).map(function (value, index) { return _data[index] ? value + _data[index] : (value ? value : '') }).join("");
}

String.prototype.formatAll = function (_keys, _data) {
  let shift = () => { _keys.shift(); return _data.shift() }
  return this.split(/\s+/).map(function (value) { return value == _keys[0] ? shift() : value }).join(" ")
}

"path/of/0/object/s/0/feature".format(0, [10,22])
//outputs
'path/of/10/object/s/22/feature'

"this is a string to replace. This string should be replaced using javascript".formatAll(["this","is","string","should","javascript"],["There","are","strings","have to","node.js"])
//outputs
'There are a strings to replace. This string have to be replaced using node.js'

"Merhaba dünya! Merhaba ay!".formatAll(["Merhaba"], ["Hello"])
//outputs
'Hello dünya! Merhaba ay!'

"Merhaba dünya! Merhaba ay!".formatAll(["Merhaba", "Merhaba"], ["Hello", "Selam"])
//outputs
'Hello dünya! Selam ay!'
发布评论

评论列表(0)

  1. 暂无评论