gpt4 book ai didi

javascript - 将句子大小写应用于可能包含 HTML 的字符串

转载 作者:行者123 更新时间:2023-11-28 18:38:45 25 4
gpt4 key购买 nike

我有一系列字符串,需要将其转换为“句子大小写”,但让事情变得更复杂的是,该字符串可能具有 html anchor 标记。

其中可能包含这样的 html:

<a href="/foo">foo</a> is a word. this is another word, and <a href="/bar">bar</a> is another.

我想应用句子大小写,输出如下:

<a href="/foo">Foo</a> is a word. This is another word, and <a href="/bar">bar</a> is another.

我可以使用任何利用 jsvbscript 的解决方案。

最佳答案

我想你可以构建一个相当幼稚的方法,简单地迭代字符串并根据遇到的情况标记条件(即它设置一个 inHtml 标志来指示它位于 HTML 标记中并设置另一个 shouldCapitalize 标志来确定它是否位于句子的开头:

function titleCaseHtmlSentence(s){
// A temporary string to hold your results
var result = '';
// Iterate through the sentence and check each character to determine if
// it is the start of a sentence, ignore this
var shouldCapitalize = true;
var inHtml = false;
for(var i = 0; i < s.length; i++){
// If this is any non tag, punctuation or letter or we are in HTML
// and haven't encountered a closing tag
if(/[^a-zA-Z\?\.\>\\<\!]/.test(s[i]) || (inHtml && s[i] != '>')){
result += s[i];
continue;
}
// If we should capitalize, check if we can
if(shouldCapitalize && /[a-zA-Z]/.test(s[i])){
// Capitalize this character
result += s[i].toUpperCase();
shouldCapitalize = false;
continue;
}
else{
result += s[i];
// If this character is '<', then we are in HTML, so ignore these
if(s[i] == '<'){
inHtml = true;
continue;
}
// If the character is a closing tag '>', then start paying attention again
if(s[i] == '>'){
inHtml = false;
continue;
}

// Determine if we hit punctuation to start a new sentence
if(/[\?\!\.]/.test(s[i])){
shouldCapitalize = true;
continue;
}
}
}
return result;
}

我相当匆忙地将它组合在一起,所以我确信这在任何意义上都远非最佳,但它应该像 seen in this example 一样工作。 .

关于javascript - 将句子大小写应用于可能包含 HTML 的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36511785/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com