从字符串JS的末尾提取子字符串

Extract sub string from last in a string JS

本文关键字:字符串 提取 JS      更新时间:2023-09-26

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

请帮忙。

在JS 中添加以下代码

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

您需要将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()的第二个参数,所以会一直延续到字符串的末尾。

function isDepreciated(S) {
    var suffix = "- depreciated";
    return S.indexOf(suffix, S.length - suffix.length) !== -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)));
    };
  };

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

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

或者使用.bind():

var isDepricated = RegExp.prototype.test.bind(/- depreciated$/);
isDepricated("string value - depreciated");
function isDepreciated(S){
    return (new RegExp(" - depriciated$").test(S));
}

使用正则表达式怎么样

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

这里已经有很多答案了(最好是带$的答案),尽管我也必须写一个,所以它也能胜任你的工作,

var somestring = "string value - depreciated";
var pattern="- depreciated";
function isDepreciated(var s)
{
    b=s.substring(s.length-pattern.length,s.length)==pattern;
}
    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

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

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

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