2012-04-06 71 views
-1

我想檢查一個字符串是否以「.php」擴展名結尾,如果不是,我想在結尾處添加.html。我已經嘗試過各種「切片」方法而沒有成功。將.html添加到字符串Javascript?

+1

@ user1317928請嘗試用代碼來解釋你的問題很好(你試過)如果可能的話,從下一次 – Devjosh 2012-04-06 17:23:38

回答

2

您可以使用正則表達式爲

var string1 = "www.example.com/index"; 
var newString = !/\.php$/i.test(string1)? string1+".html": string1; 
// newString = "www.example.com/index.html" 
+1

假設「.PHP」在中間的某個地方發生的無病理情況。 – 2012-04-06 17:16:49

+2

@DaveNewton不,他沒事。注意標記字符串結尾的'$'。 – Imp 2012-04-06 17:23:52

+1

@Imp他補充說,之後,戴夫在當時是正確的。 – Paulpro 2012-04-06 17:39:20

0

嘗試是這樣的

function isPHP(str) 
{ 
    return str.substring(str.length - 4) == ".php"; 
} 

那麼你可以做

str = isPHP(str) ? str : str + ".html"; 
+1

不是'(str.length - 4)'嗎? – 2012-04-06 17:15:13

+1

@斯科特,正確的,爲現場歡呼。 – 2012-04-06 17:18:58

1

使用(yourstring + '.html').replace(/\.php\.html$/, '.php')做到這一點:

var str1 = 'one.php'; 
var str2 = 'two'; 
var str3 = '.php.three.php'; 
var str4 = '.php.hey'; 

console.log((str1 + '.html').replace(/\.php\.html$/, '.php')); // Prints one.php 
console.log((str2 + '.html').replace(/\.php\.html$/, '.php')); // Prints two.html 
console.log((str3 + '.html').replace(/\.php\.html$/, '.php')); // Prints .php.three.php 
console.log((str4 + '.html').replace(/\.php\.html$/, '.php')); // Prints .php.hey.html 
1

或許:

function appendHTML(string) { 
    var html = string; 
    if (string.lastIndexOf('.php') === (string.length - 4)) { 
     html += '.html'; 
    } 
    return html; 
} 
1

使用正則表達式來解決你的問題。 /.php$/是一個正則表達式,檢查是否一個字符串與 '.PHP'

有關詳細信息讀取結束時:http://www.w3schools.com/js/js_obj_regexp.asp

例如代碼:

str = "http://abc.com"; 
str = (/\.php$/.test(str)) ? str : str + '.html'; // this is the line you want. 

str === "http://abc.com.html" // returns true 
1

那麼,slice()適用於此任務。

var s = "myfile.php"; 

if (s.slice(-4) != ".php") 
    s = s.slice(0, -4) + ".html";