我正在开发一个Javascript函数来基本上改变"她是"他们是"他们是"当一个人没有选择性别时。它将允许性别中立的文本。我找到了这个脚本,但想看看是否有更好的方法使文本性别中立。
function personalize(template, options) {
var GENDERS = ['neutral', 'female', 'male'];
var PERSONS = ['first', 'second', 'third'];
var CASES = ['subjective', 'objective', 'possessive', 'reflexive'];
var PRONOUNS = {
'first': {
'subjective': 'I',
'objective': 'me',
'possessive': 'my',
'reflexive': 'myself'
},
'second': {
'subjective': 'you',
'objective': 'you',
'possessive': 'your',
'reflexive': 'yourself'
},
'third': {
'neutral': {
'subjective': 'they',
'objective' : 'them',
'possessive': 'their',
'reflexive' : 'themself'
},
'female': {
'subjective': 'she',
'objective' : 'her',
'possessive': 'her',
'reflexive' : 'herself'
},
'male': {
'subjective': 'he',
'objective' : 'him',
'possessive': 'his',
'reflexive' : 'himself'
}
}
};
var VERBS = ['are', 'are|not', 'have', 'have|not'];
var CONJUGATIONS = {
'first': {
'have': 'have',
'have|not': 'haven\'t',
'are': 'am',
'are|not': 'am not'
},
'second': {
'have': 'have',
'have|not': 'haven\'t',
'are': 'are',
'are|not': 'aren\'t'
},
'third': {
'have': 'has',
'have|not': 'hasn\'t',
'are': 'is',
'are|not': 'isn\'t'
}
};
var gender = options.gender || 'neutral';
var person = options.person || 'third';
var name = options.name || 'Anon';
var result = template;
var ABBREVIATIONS = {
'have': '\'ve',
'has': '\'s',
'are': '\'re',
'is': '\'s',
'am': '\'m'
};
function replaceVerb(str, whitespace, match) {
var replacer = CONJUGATIONS[person][match];
return ABBREVIATIONS[replacer] || whitespace + replacer;
}
for (var i = 0; i < VERBS.length; i++) {
var verb = VERBS[i];
result = result.replace(new RegExp('(\\s*){{\\s*(' + verb + ' [|not]*)\\s*}}','g'), replaceVerb);
}
function replacePronoun(str, match) {
var replacer = '';
if (person == 'third') {
if (match.indexOf('|name') > -1) {
replacer = name;
} else {
replacer = PRONOUNS[person][gender][pronoun_case];
}
} else {
replacer = PRONOUNS[person][pronoun_case];
if (match.charAt(0) == match.charAt(0).toUpperCase()) {
replacer = replacer.charAt(0).toUpperCase() + replacer.slice(1);
}
}
return replacer;
}
for (var i = 0; i < CASES.length; i++) {
var pronoun_case = CASES[i];
var template_pronoun = PRONOUNS.third.neutral[pronoun_case];
result = result.replace(new RegExp('{{\\s*(' + template_pronoun + '[|name]*)\\s*}}','gi'), replacePronoun);
}
return result;
}
答案 0 :(得分:0)
JavaScript String对象具有内置的查找和替换功能。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
可以像这样使用
this()