0

I am new in javascript. I want to replace string value from array if array key value match with string value
Here is my following code:

var arr= [];
arr[11] = 'XYZ';
arr[12] = 'ABC';

var string = "11-12";

My Output will be :

var str ="XYZ-ABC";
6
  • 3
    what have you already tried? Commented Aug 15, 2016 at 8:53
  • Will the values in string be unique, will the array value never contain a array index? Commented Aug 15, 2016 at 8:53
  • Values in the string is unique Commented Aug 15, 2016 at 8:54
  • does the string contain only spaces and dashes as seperator? Then you could try to split it up Commented Aug 15, 2016 at 8:54
  • can you please explain a little better what are you trying to achieve? Commented Aug 15, 2016 at 8:55

3 Answers 3

4

Use String#replace method with a callback.

var arr = [];
arr[11] = 'XYZ';
arr[12] = 'ABC';

var string = "11 - 12";

// match all digits in string and replace it with 
// corresponding value in `arr`
var res = string.replace(/\d+/g, function(m) {
  return arr[m];
})

console.log(res);

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

Comments

0

You can use regx.test() to get the Boolean value to check if it is character or not .

var arr = [];
arr[11] = 'XYZ';
arr[12] = 'ABC';

if(/[a-zA-Z\s]+/.test(arr[11])&&/[a-zA-Z\s]+/.test(arr[12])){
var str=arr[11]+ " " +arr[12];
}

Comments

0

You just need array methods (split map and join), neither regex nor jquery:

var str = string.split("-").map(elem => arr[elem]).join("-");

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.