2

我需要编写 JS 函数,如果字符串包含- depreciated在其最后一个否则返回 true,否则返回 false。

例如:

var somestring = "string value - depreciated";

在上面的例子中,函数应该返回 true。

function isDepreciated(var S)
{
    //Need to check for substring in last
    //return true or false
}

一种可能的解决方案是使用search函数,但这意味着如果- depreciated出现在字符串中,那么它也将返回 true。我真的需要找到天气子字符串是否在最后。

请帮忙。

4

9 回答 9

2

在您的 JS 中添加以下代码

function isDepreciated(string){
   return  /(-depreciated)$/.test(string);
}
于 2013-07-29T08:41:26.593 回答
1

你可以使用柯里化:http ://ejohn.org/blog/partial-functions-in-javascript/

Function.prototype.curry = function() {
    var fn = this, args = Array.prototype.slice.call(arguments);
    return function() {
      return fn.apply(this, args.concat(
        Array.prototype.slice.call(arguments)));
    };
  };

使用 helper curry 函数,您可以创建您的 isDetricated 检查:

String.prototype.isDepricated = String.prototype.match.curry(/- depreciated$/);

"string value - depreciated".isDepricated();

或使用.bind()

var isDepricated = RegExp.prototype.test.bind(/- depreciated$/);

isDepricated("string value - depreciated");
于 2013-07-29T08:53:08.777 回答
1
function isDepreciated(S) {
    var suffix = "- depreciated";
    return S.indexOf(suffix, S.length - suffix.length) !== -1;
}
于 2013-07-29T08:48:36.857 回答
1

您需要.substr()结合.length属性使用 Javascript 字符串方法。

function isDepreciated(var id)
{
    var id = "string value - depreciated";
    var lastdepreciated = id.substr(id.length - 13); // => "- depreciated"
    //return true or false check for true or flase
}

这将获取从 id.length - 13 开始的字符,并且由于 .substr() 的第二个参数被省略,因此继续到字符串的末尾。

于 2013-07-29T08:42:08.860 回答
0

很多答案已经在这里(首选带有 $ 的答案),即使我也必须写一个,所以它也可以完成你的工作,

var somestring = "string value - depreciated";
var pattern="- depreciated";

function isDepreciated(var s)
{
    b=s.substring(s.length-pattern.length,s.length)==pattern;
}
于 2013-07-29T09:13:18.110 回答
0
function isDepreciated(S){
    return (new RegExp(" - depriciated$").test(S));
}
于 2013-07-29T08:48:58.243 回答
0

使用正则表达式怎么样

  var myRe=/depreciated$/;
  var myval = "string value - depreciated";
  if (myRe.exec(myval)) {
    alert ('found');
  }
  else{
    alert('not found');
  }
于 2013-07-29T08:49:18.713 回答
-1

好的,我还没有在浏览器上运行这段代码,但这应该给出一个基本的想法。如果需要,您可能需要调整一些条件。

var search = "- depricated";
var pos = str.indexOf(search);

if(pos > 0 && pos + search.length == str.length){
    return true;
}
else{
   return false;
}

编辑:indexOf()返回字符串的起始索引。

于 2013-07-29T08:40:18.583 回答
-1
    function isDeprecated(str) {
          return ((str.indexOf("- depreciated") == str.length - "- depreciated".length) ? true : false);
    }

    isDeprecated("this")
    false

    isDeprecated("this - depreciated")
    true

    isDeprecated("this - depreciated abc")
    false
于 2013-07-29T08:44:51.357 回答