我想檢查一個字符串是否以「.php」擴展名結尾,如果不是,我想在結尾處添加.html。我已經嘗試過各種「切片」方法而沒有成功。將.html添加到字符串Javascript?
-1
A
回答
2
您可以使用正則表達式爲
var string1 = "www.example.com/index";
var newString = !/\.php$/i.test(string1)? string1+".html": string1;
// newString = "www.example.com/index.html"
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";
相關問題
- 1. 將字符串添加到字符串
- 2. 如何將字符串中的javascript塊添加到html中?
- 3. 將字符添加到字符串
- 4. 將字符添加到字符串
- 5. Python - 將字符添加到字符串
- 6. 將字符添加到字符串
- 7. 將字符添加到JSON字符串
- 8. 將字符添加到字符串vb.net
- 9. Java將字符添加到字符串
- 10. 在Javascript中將字符添加到字符串中
- 11. Javascript將字符串返回到Html
- 12. 將字符串與HTML傳遞到JavaScript
- 13. 將HTML(json字符串)拉到javascript
- 14. 添加HTML字符串屬性添加到html元素
- 15. 使用JavaScript將按鈕中的字符串添加到HTML字段
- 16. Javascript添加到http://後的字符串?
- 17. 將數字添加到字符串?
- 18. 將數字添加到字符串?
- 19. 基於字符計數將字符串添加到字符串
- 20. 添加字符串的JavaScript
- 21. 的JavaScript的onclick添加到HTML字符串
- 22. 將NSMutableDictionary添加到NSMutableDictionary將字典添加爲字符串
- 23. 將字符串添加到逐字字符串文字
- 24. 將字符串添加到字符串的數字和數字
- 25. 將char []添加到char **(字符串到字符串列表)
- 26. vb.net字符串concat將vbCrlf文字添加到字符串
- 27. 使用JavaScript將HTML字符串加載到DOM樹中
- 28. 將HTML Textarea內容添加到使用Javascript的字符數組
- 29. 將字符串屬性添加到CoreDataBooks
- 30. 如何將字符串添加到JsonArray
@ user1317928請嘗試用代碼來解釋你的問題很好(你試過)如果可能的話,從下一次 – Devjosh 2012-04-06 17:23:38