gpt4 book ai didi

javascript - 返回这些字符之一之前的字符串

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

我想在这些元素之一之前返回一个字符串。如果字符串仍然超过 80 个字符,我将返回它们直到 80 个字符。

"Hello! my name is Marcel. I am 30 years old -" => "Hello!"

"Hello, my name is Marcel. I am 30 years old," => "Hello, my name is Marcel."

"Hello my name is Marcel <br/> I am 30 years old -" => "Hello my name is Marcel"

这是我尝试过的,我觉得必须有更简单的东西:

 getStrWithMinOfElements(str){
var arr=[str.indexOf('.'), str.indexOf('!'), str.indexOf('<br'), str.indexOf('-')];
var index = arr.indexOf(-1);
if (index > -1) {
arr.splice(index, 1);
}
index = arr.indexOf(-1);
if (index > -1) {
arr.splice(index, 1);
}
index = arr.indexOf(-1);
if (index > -1) {
arr.splice(index, 1);
}

var min = Math.min(...arr);
if(min<8 || min>80) return str.substring(0,80);
return str.substring(0,min);
}

最佳答案

您可以匹配要分隔的字符的第一个实例,并将其后面的任何内容替换为空字符串,并从替换的字符串中获取长度为 80 的子字符串

let strs = ["Hello! my name is Marcel. I am 30 years old -","Hello, my name is Marcel. I am 30 years old,","Hello my name is Marcel<br/> I am 30 years old -"]

strs.forEach(str=>{
let strReplaced = str.replace(/(\.|!|<br\/>).*$/,"$1")
let final = strReplaced.substring(0,80)
console.log(final)
})

关于javascript - 返回这些字符之一之前的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57324141/

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