Home > Software design >  How Do I Replace A Sentence with RegExp With Word List from Array Element in Javascript?
How Do I Replace A Sentence with RegExp With Word List from Array Element in Javascript?

Time:02-15

I'm making a simple site with HTML JavaScript to change matched letters in a word/sentence to specific letter based on list from Array element.

Let's say I have this multidimensional array:

var wordList = [
  ["dj", "j"],
  ["ch", "kh"],
];

So if anyone write "Djakarta", the site will change it to "Jakarta", based on the match from the array. Same like "Chairul", will be changed to "Khairul".

Here's my code, so far:

/* Words that will be changed */
var wordList = [
  ["dj", "j"],
  ["ch", "kh"],
];

/* Main function */
function main() {
  // Initialize #formEjaanLama
  formEjaanLama = document.getElementById("formEjaanLama");

  // Get value #formEjaanLama
  valueFormEjaanLama = formEjaanLama.value;

  // Initialize #formEjaanBaru
  formEjaanBaru = document.getElementById("formEjaanBaru");

  // Mulai perubahan
  for (var arrayIndex in wordList) {
    var regex = new RegExp(wordList[arrayIndex][0], "gi");
    valueFormEjaanLama.replaceAll(regex, wordList[arrayIndex][1]);
  }
  console.log(valueFormEjaanLama);
}

arrayIndex is the number of current Array index from for loop. So wordList[arrayIndex][0] equals to dj and ch. And so on.

I ran the site and inputted Djakarta, but the word wasn't changed at all.

Example Usage

Do I miss something here? Thank you. Let me know if you need more details.

RegExp reference: https://stackoverflow.com/a/494046/13293193

CodePudding user response:

Thats because replaceAll and replace methods, "return" a string and not replace the value of the string used for that method.

Which means when you use valueFormEjaanLama.replaceAll(regex, wordList[arrayIndex][1]); it returns the correct result but then there is no code to use the returned result, so you dont get your desired objective.

Change the code to :

  for (var arrayIndex in wordList) {
    var regex = new RegExp(wordList[arrayIndex][0], "gi");
    valueFormEjaanLama = valueFormEjaanLama.replaceAll(regex, wordList[arrayIndex][1]);
  }

Also your regex to : var regex = new RegExp(wordList[arrayIndex][0], "gi")

will match any word which has 'dj' or 'ch' anywhere in the value of valueFormEjaanLama eg:it will match texts like: 'textdj' or 'textdjtext' etc. So change it to var regex = new RegExp("\\b" wordList[arrayIndex][0], "gi") This will match only if words from wordlist are at the beginning of value of valueFormEjaanLama.

CodePudding user response:

You just need to reassign the value to the same variable then your code will work.

for (var arrayIndex in wordList) {
    var regex = new RegExp(wordList[arrayIndex][0], "gi");
    valueFormEjaanLama = valueFormEjaanLama.replaceAll(regex, wordList[arrayIndex][1]);
}
  • Related