我从Api数据中检索Url,如下所示:
<div class="row copy-text">
<a href="{{copy.Url}}" target="_blank" style="text-decoration: underline !important;">{{copy.Title}}</a>
</div>
我想检查一下Url是否有https://作为前缀,如果它没有,我想添加。由于没有https://,Url就是这样的localhost的根目录 - localhost / www.test.com /
答案 0 :(得分:1)
您可以创建一个取值为copy.Url
的管道,并在需要时将其前缀为“https://”。
功能将是:
function addHttps(input) {
const prefix = 'https://';
let output = input;
if ((input).substr(0, prefix.length) !== prefix) {
output = prefix + input;
}
return output;
}
console.log('aaa');
console.log('https://aaa');
您可以将其用作:
<a href="{{ copy.Url | httpsPrefix }}" target="_blank" style="text-decoration: underline !important;">{{copy.Title}}</a>
创建名为https-prefix.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'httpsPrefix'})
export class httpsPrefixPipe implements PipeTransform {
transform(value: string): number {
const prefix = 'https://';
let output = value;
if ((value).substr(0, prefix.length) !== prefix) {
output = prefix + value;
}
return output;
}
}
现在您可以将管道用作:
<a href="{{ copy.Url | httpsPrefix }}" target="_blank" style="text-decoration: underline !important;">{{copy.Title}}</a>
答案 1 :(得分:0)
看看这是否适合您。你需要导入lodash for startsWith才能工作。
function checkString(input) {
if(_.startsWith(input, 'https')) {
console.log("Yay, starts with https")
} else {
input = "https://" + input;
console.log(input);
}
}
checkString('https://abc');
checkString('localhost');
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
&#13;