Javascript 尝试检索所有前导的大写字符,这些字符前面带有空格、连字符、撇号或字符串开头

Javascript 尝试检索所有前导的大写字符,这些字符前面带有空格、连字符、撇号或字符串开头,javascript,regex,Javascript,Regex,正在尝试检索所有前导大写字符,前面带有空格、连字符、撇号或字符串开头 示例: var text = "This is a sample about about JJohnny Apple-Seed and old Mc'Donald."; text.match(/[A-Z]/g) // returns --> ["T", "J", "J", "A", "S", "M", "D"] var str = "This is a story about JJohnny Apple-Seed

正在尝试检索所有前导大写字符,前面带有空格、连字符、撇号或字符串开头

示例:

var text = "This is a sample about about JJohnny Apple-Seed and old Mc'Donald.";
text.match(/[A-Z]/g)  // returns  -->  ["T", "J", "J", "A", "S", "M", "D"]
var str = "This is a story about JJohnny Apple-Seed and Old Mc'Donald.";
var myRe = /\b([A-Z])/g;

var myArray;
while ((myArray = myRe.exec(str)) !== null)
{
  var msg = "Found " + myArray[0] + ".  ";
  msg += "Next match starts at " + myRe.lastIndex-1;
  console.log(msg);
}
所需输出:
[“T”、“J”、“A”、“S”、“M”、“D”]

更新的最终解决方案:

var text = "This is a sample about about JJohnny Apple-Seed and old Mc'Donald.";
text.match(/[A-Z]/g)  // returns  -->  ["T", "J", "J", "A", "S", "M", "D"]
var str = "This is a story about JJohnny Apple-Seed and Old Mc'Donald.";
var myRe = /\b([A-Z])/g;

var myArray;
while ((myArray = myRe.exec(str)) !== null)
{
  var msg = "Found " + myArray[0] + ".  ";
  msg += "Next match starts at " + myRe.lastIndex-1;
  console.log(msg);
}

标准的
\b
(单词边界)元字符应该可以帮助您实现:

text.match(/\b([A-Z])/g)
给出:

["T", "J", "A", "S", "M", "D"]