[英]Regex string ends with not working in Javascript
我對正則表達式不是很熟悉。 我試圖測試一個字符串是否以另一個字符串結尾。 當我期望為真時,下面的代碼返回 null。 代碼有什么問題?
var id = "John";
var exists ="blahJohn".match(/id$/);
alert(exists);
好吧,使用這種方法,您需要使用RegExp
構造函數,使用您的id
變量構建正則表達式:
var id = "John";
var exists = new RegExp(id+"$").test("blahJohn");
alert(exists);
但是有很多方法可以實現這一點,例如,您可以獲取字符串的最后一個id.length
字符,並將其與id
進行比較:
var id = "John";
var exist = "blahJohn".slice(-id.length) == id; // true
您需要使用RegExp()
對象來執行此操作,而不是文字:
var id = "John",
reg = new RegExp(id+"$");
alert( reg.test("blahJon") );
也就是說,如果您在運行前不知道要測試的值。 否則你可以這樣做:
alert( /John$/.test("blahJohn") );
我喜歡@lonesomeday 的解決方案,但我喜歡在這些場景中擴展 String.prototype。 這是我對他的解決方案的改編
String.prototype.endsWith = function (needle) {
return needle === this.substr(0 - needle.length);
}
所以可以檢查
if(myStr.endsWith("test")) // Do awesome things here.
可口...
var id = "John";
(new RegExp(`${id}$`)).test('blahJohn'); // true
(new RegExp(`${id}$`)).test('blahJohna'); // false
`${id}$` 是一個 JavaScript 模板字符串,將被編譯為 'John$'。
RegExp 中 John 之后的$
代表字符串結尾,因此被測試的字符串必須在 id 值(即 John)之后沒有任何內容才能通過測試。
new RegExp(`${id}$`) - 將其編譯為/John$/
(所以如果 id 不應該是動態的,你可以只使用 /John$/ 而不是 new RegExp(`${id}$`) )
嘗試這個 -
var reg = "/" + id + "$/";
var exists ="blahJohn".match(reg);
更好的方法是使用RegExp.test
:
(new RegExp(id + '$')).test('blahJohn'); // true
(new RegExp(id + '$')).test('blahJohnblah'); // false
更好的是構建一個像這樣的簡單函數:
function strEndsWith (haystack, needle) {
return needle === haystack.substr(0 - needle.length);
}
strEndsWith('blahJohn', id); // true
strEndsWith('blahJohnblah', id); // false
如果您需要它來替換功能,請考慮以下 regExp:
var eventStr = "Hello% World%";
eventStr = eventStr.replace(/[\%]$/, "").replace(/^[\%]/, ""); // replace eds with, and also start with %.
//輸出:eventStr = "Hello% World";
var id = new RegExp("John");
var exists ="blahJohn".match(id);
alert(exists);
嘗試這個
為什么使用正則表達式? 它的價格昂貴。
function EndsWith( givenStr, subst )
{
var ln = givenStr.length;
var idx = ln-subst.length;
return ( giventStr.subst(idx)==subst );
}
更容易和更具成本效益,是嗎?
剛剛創建了這個輔助函數,我發現它比修改正則表達式並每次都重新創建一個更有用和更干凈。
/**
* @param {string} str
* @param {RegExp} search
* @returns {boolean}
*/
function regexEndsWith (str, search, {caseSensitive = true} = {})
{
var source = search.source
if (!source.endsWith('$')) source = source + '$'
var flags = search.flags
if (!caseSensitive && !flags.includes('i')) flags += 'i'
var reg = new RegExp(source, flags)
return reg.test(str)
}
以這種方式使用它:
regexEndsWith('can you Fi nD me?', /fi.*nd me?/, {caseSensitive: false})
這是一個使用正則表達式的字符串原型函數。 您可以使用它來檢查是否有任何字符串對象以特定的字符串值結尾:
原型功能:
String.prototype.endsWith = function (endString) {
if(this && this.length) {
result = new RegExp(endString + '$').test(this);
return result;
}
return false;
}
示例用法:
var s1 = "My String";
s1.endsWith("ring"); // returns true;
s1.endsWith("deez"); //returns false;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.