Prakash Jadhav
Prakash Jadhav

Reputation: 95

Javascript replace word from string with matching array key

my question is bit simple but still dont know where i am actually making mistake.

I am trying to replace the word from string. I already have a array which holds the key and value. User typing something in the input box, if the input value match with the array key, then respective value of key should have to replace within the string. It works fine when i enter ast in the textbox the ast get replaced with array value 'at least'. Then after i continued the typing and if i enter another word like astronaut, then after problem rises because the word astronaut also contains the "ast" which already in the array, i dont want to replace astronaut i want to only replace ast.

Will anyone point me where i am making mistake.

Following is my code...

var down = document.getElementById('mtpo');

function rude(str) {

  var Obj = {
    ast: 'at least',
    ateo: 'at the end of ',
    ateot: 'at the end of the ',
    atsr: 'After the speakers remark, there will be a question-and-answer session',
    atst: 'at the same time',
    atto: 'attributable to',
    atx: 'after tax',
    av: 'average',
    avg: 'average',
    aw: 'associated with',
    awa: 'as well as',
    awd: 'as we discussed',
    aya: 'a year ago',
    aycs: 'as you can see',
    ba: 'be able to',
    bec: 'because',
    bey: 'by the end of the year',
    bly: 'basically',
    bn: 'billion',
    bng: 'begining',
    bns: 'business',

  };
  var RE = new RegExp(Object.keys(Obj).join("|"), "gi");



  down.value = str.replace(RE, function(matched) {
    return Obj[matched];
  });

}


$("#mtpo").keyup(function(event) {

  var text;
  if (event.keyCode == 32) {
    var text = rude($(this).val());
    $(this).val(text);
    //$("someText").html(text);
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="mtpo"></textarea>

Upvotes: 2

Views: 1250

Answers (2)

CertainPerformance
CertainPerformance

Reputation: 370769

One option is to add word boundaries around every short word you're matching. For example, to match ast or ateo, you would use the regular expression

\b(?:ast|ateo)\b

Just repeat the pattern for the rest of the keys:

const patternStr = '\\b(?:' + Object.keys(Obj).join("|") + ')\\b';
const pattern = new RegExp(patternStr, "gi");

var Obj = {
  ast: 'at least',
  ateo: 'at the end of ',
  ateot: 'at the end of the ',
  atsr: 'After the speakers remark, there will be a question-and-answer session',
  atst: 'at the same time',
  atto: 'attributable to',
  atx: 'after tax',
  av: 'average',
  avg: 'average',
  aw: 'associated with',
  awa: 'as well as',
  awd: 'as we discussed',
  aya: 'a year ago',
  aycs: 'as you can see',
  ba: 'be able to',
  bec: 'because',
  bey: 'by the end of the year',
  bly: 'basically',
  bn: 'billion',
  bng: 'begining',
  bns: 'business',
};

const patternStr = '\\b(?:' + Object.keys(Obj).join("|") + ')\\b';
const pattern = new RegExp(patternStr, "gi");

function rude(str) {
  return str.replace(pattern, function(matched) {
    console.log('ok ', matched, Obj[matched]);
    return Obj[matched];
  });
}

$("#mtpo").keyup(function(event) {
  if (event.keyCode == 32) {
    var text = rude($(this).val());
    $(this).val(text);
    //$("someText").html(text);
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="mtpo"></textarea>

Upvotes: 6

Zlatko
Zlatko

Reputation: 19569

Maybe matching the whole word will do it for you: Something like:

\b(ast)\b

\b is a "word boundary" here. So in your case try this.

const shortCuts = {
  ast: 'at least',
  ateo: 'at the end of ',
  ateot: 'at the end of the ',
  atsr: 'After the speakers remark, there will be a question-and-answer session',
  atst: 'at the same time',
  atto: 'attributable to',
  atx: 'after tax',
  av: 'average',
  avg: 'average',
  aw: 'associated with',
  awa: 'as well as',
  awd: 'as we discussed',
  aya: 'a year ago',
  aycs: 'as you can see',
  ba: 'be able to',
  bec: 'because',
  bey: 'by the end of the year',
  bly: 'basically',
  bn: 'billion',
  bng: 'begining',
  bns: 'business',
};
const re = new RegExp(
  Object.keys(shortCuts)
  .map(key => `\\b${key}\\b`)
  .join("|"), "gi");


function replace(word) {
  return word.replace(re, matched => shortCuts[matched]);
}

const testStrings = ['I want ast this to be replaced', 'But not the astronaut'];

testStrings.forEach(str => console.log(replace(str)));

Upvotes: 2

Related Questions