Forum Moderators: open
var str = 'John';
var chars = {
'John' : 'Jack'
};
// I want to replace "John" with "Jack
str = str.replace(/(\w+)/, chars['$1']); var str = 'John is ';
str = str.replace(/(\w+)\s\w+/, '$1'); str = str.replace(/(\w+)\s\w+/, chars['John']); str = str.replace(/(\w+)/g,
function(v, match) {
if (chars[match])
return chars[match];
else return v;
}
);
var str = 'John is';
var chars = {
'John': 'Jack'
};
var regexp = /(\w+)/;
var input = 'John'; // Note, this could be a param of a function
var match = chars[input];
str = match === undefined ? str : str.replace(regexp, match);
let str = "John is"
str.match(/(\w+)/);
const matched = RegExp.$1
str = matched ? str.replace(matched, chars[matched]) : str
str = match !== undefined ? str.replace(regexp, match) : str;
const person = 'John';
const template = 'John is here';
const map = {
John: 'Jack'
};
function replaceWithMapValue(input, target, map) {
const regexp = /(\w+)/;
const value = map[input];
const result = value !== undefined ? target.replace(regexp, value) : target;
return result;
}
console.log(replaceWithMapValue(person, template, map));