首字母大写函数也在撇号后大写

时间:2016-11-03 23:50:57

标签: javascript

我有一个函数可以将每个单词的第一个字母大写:

create table courses_instructors
(
courseID int foreign key references Course(C_ID) not null,
instructorID int foreign key references Instructor(I_ID) not null,
primary key (courseID, instructorID), --coourseID and instructorID combined is the composite PK
courseTerm varchar(50) not null,
courseNumber int not null,
courseLocation varchar(50),
courseTime varchar(50),
courseMaxOccupancy int,
courseSeatAvailable int
)

create table courses_students
(
studentID int foreign key references student(S_ID) not null,
courseID int, -- foreign key -- I want this value to the be value that represents the composite PK from the courses_instructors
primary key(studentID, courseID), -- these 2 fields combined would make the composite PK, but with the courseID value I will be able to identify who is the instructor for a course and the other details from the course_instructor table
courseOutcome varchar(50)
)

它也是在撇号之后大写:

function format(str){
    str = str.replace(/\b[a-z]/g, function(letter) {
        return letter.toUpperCase();
    });
    return str;
}

理想情况下,我希望它在撇号后大写如果它是一个名字(例子2),而不是(例子3)。我怎样才能解决这个问题? Fiddle here

编辑:我不认为这是this question的副本,因为我特别询问不要将大写,但是在其他撇号之后没问题。

1 个答案:

答案 0 :(得分:3)

不幸的是,Javascript正则表达式没有lookbehind语法在一个正则表达式中完成所有操作,但是,您可以分两步完成。现在是大写,但事后是小'S

var strings = [
    "mark", 
    "mark o'loughlan",
    "mark's audi"
]

var returnValue = "";
function format(str){
    str = str.replace(/\b[a-z]/g, function(letter) { return letter.toUpperCase(); });
    str = str.replace(/'(S)/g, function(letter) { return letter.toLowerCase(); });
    return str;
}

strings.forEach(function(string){
    console.log(format(string));
});