从字符串JS的末尾提取子字符串
Extract sub string from last in a string JS
我需要编写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()
返回字符串的起始索引。
相关文章:
- 如何在Javascript中从字符串中提取某些单词
- innerHTML的子字符串可以在初始调用时提取吗
- 从字符串中提取年份的Javascript正则表达式
- 使用javascript从字符串中提取浮点数
- 如何使用另一个字符串作为模板从字符串中提取数据
- Regex模式匹配,从Javascript中的字符串中提取时间,结果出乎意料
- 正在从字符串中提取日期
- 使用gulp-angular gettext从JS文件中提取字符串不起作用
- 如何在系列数据中包含字符串以提取工具提示点格式
- 通过正则表达式从字符串中提取Url
- 正则表达式,用于从html格式的字符串中提取文本
- Javascript:如何通过Regexp从属性中提取字符串
- 如何删除“"使用javascript从字符串中提取字符
- 如何从由“”分隔的字符串中提取最后一个文本|&”;
- 从html标记格式的字符串中提取键值对
- 简单的javascript字符串提取
- 如何通过jquery或javascript从日期字符串提取日期格式
- 在Javascript中从字符串提取值到数组
- 如何将元组字符串提取到数据结构中
- 我如何从JavaScript中的URL字符串提取值