0

How to read object from array, or what I'm doing wrong?

Here is my array map with object as key:

var nj = new RegExp("nj","g");
var replaceMap = {nj:"ň"};

But while looping the array I can't get valid object reference.

for (var replaceValue in replaceMap) {
   text = text.replace(replaceValue, replaceMap[replaceValue]);
}

When replace is performing then it replaces only one instance of search text - RegExp object modifier for global match ("g") is ignored. I suppose, that I didn't get a valid object reference in replaceValue. When I used nj variable replace operation then it works fine.

Thanks in advance.

0

3 Answers 3

1

Reason:

When you refer something like for(var x in o){...}, then x is a javascript string, and not an object.

So in your case it is "nj" and not RegExp object nj

hence only the first match gets replaced.

You can test it like this:

var a=new RegExp("kk","g");
var mymap={a:"jjj"};

for(var k in mymap){
console.log(k+"  "+typeof k);
}

The console output will give you the typeof the key

Sign up to request clarification or add additional context in comments.

Comments

0

Check this in your browser console (press F12 in Chrome of Firefox):

>var aa="hello";
undefined
>var replaceMap={aa: "Hello2"}
undefined
>replaceMap
Object {aa: "Hello2"}

This is the equivalent code:

var aa="hello";
var replaceMap={};
replaceMap.aa="Hello2";

replace.aa has nothing to do with variable aa

But you can fix it interchanging keys and values in your map:

var replaceMap = {"ň": nj};
for (var replaceValue in replaceMap) {
   text = text.replace(replaceMap[replaceValue], replaceValue);
}

Comments

0
text = text.replace(/nj/g, 'ň');

This should perform the same thing

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.