从字符串JS中的last中提取子字符串

时间:2013-07-29 08:35:55

标签: javascript

我需要编写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。我真的需要找到天气子串在最后与否。

请帮忙。

9 个答案:

答案 0 :(得分:2)

在JS中添加以下代码

function isDepreciated(string){
   return  /(-depreciated)$/.test(string);
}

答案 1 :(得分:1)

您希望将Javascript字符串方法.substr().length属性结合使用。

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()的第二个参数,因此继续到字符串的末尾。

答案 2 :(得分:1)

function isDepreciated(S) {
    var suffix = "- depreciated";
    return S.indexOf(suffix, S.length - suffix.length) !== -1;
}

答案 3 :(得分:1)

您可以使用currying: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)));
    };
  };

使用辅助咖喱功能,您可以创建isDepricated支票:

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

"string value - depreciated".isDepricated();

或使用.bind()

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

isDepricated("string value - depreciated");

答案 4 :(得分:0)

function isDepreciated(S){
    return (new RegExp(" - depriciated$").test(S));
}

答案 5 :(得分:0)

如何使用正则表达式

  var myRe=/depreciated$/;
  var myval = "string value - depreciated";
  if (myRe.exec(myval)) {
    alert ('found');
  }
  else{
    alert('not found');
  }

答案 6 :(得分:0)

已经有很多答案(优先考虑的是那个),即使我也必须写一个,所以它也会完成你的工作,

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

function isDepreciated(var s)
{
    b=s.substring(s.length-pattern.length,s.length)==pattern;
}

答案 7 :(得分:-1)

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

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

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

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

答案 8 :(得分:-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
相关问题