Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/406.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 字符串删除最后一个连字符后的所有内容_Javascript - Fatal编程技术网

Javascript 字符串删除最后一个连字符后的所有内容

Javascript 字符串删除最后一个连字符后的所有内容,javascript,Javascript,在JavaScript中,如果最后一个连字符是一个数字,有没有办法删除它后面的所有内容 product-test-grid-2 所以结果只能是: product-test-grid 正在尝试使用此资源: 'product-test-grid-2'.replace(/(?您可以使用带有replace的简单正则表达式 例如 /-\d+$/=一个破折号后跟一个或多个数字\d+,位于$末尾 const reLast=/-\d+$/; const test1='product-test-grid-2

在JavaScript中,如果最后一个连字符是一个数字,有没有办法删除它后面的所有内容

product-test-grid-2
所以结果只能是:

product-test-grid
正在尝试使用此资源:


'product-test-grid-2'.replace(/(?您可以使用带有replace的简单正则表达式

例如

/-\d+$/
=一个破折号后跟一个或多个数字
\d+
,位于
$
末尾

const reLast=/-\d+$/;
const test1='product-test-grid-2';
const test2='产品测试网格nan';
console.log(test1.replace(reLast.);
console.log(test2.replace(reLast,);
用“-”分隔,检查最后一项是否是数字:如果是,则用“-”连接:

句子=“product-test-grid-2”;
单词=句子。拆分(“-”);
if(words[words.length-1].match(/^\d+$/)words.pop();
结果=words.join(“-”);

console.log(result);
您可以使用
reglx
执行此操作,但在我看来这似乎有些过分了

我会那样做的

const str='product-test-grid-2'
const pos=str.lastIndexOf('-'))
常量res=str.slice(0,位置)

console.log(res)
简单的JS,不涉及正则表达式

const label='product-test-grid-2'。拆分('-');
!isNaN(+label[label.length-1])?label.pop():“”;
console.log(label.join('-');
//您可以将其封装到函数中
函数formatLabel(标签){
label=label.split('-');
!isNaN(+label[label.length-1])?label.pop():“”;
返回标签。连接('-');
}
//2应在末端移除
console.log(formatLabel('product-test-grid-2');
//两个应该保持不变

console.log(formatLabel('product-test-grid-two');
单词=句子。拆分(“-”);if(单词[words.length-1]。匹配(/^\d+$/)单词。pop();结果=单词。连接(“-”)
@alanmithsmith4785运行我的答案中的代码以获得一个纯JS工作模式solution@alansmith4785是的,它会给你具体的职位的最后位置character@Yoel您的答案不会检查最后一个字符是数字还是数字not@alansmith4785是的,我已经修改了代码片段,使其显示一个没有数字的代码,
nan
。你说like regex是一件坏事……),可能值得一提的是,正则表达式的速度快了5倍以上。@Keith我没有说正则表达式不好,只是对于这个简单的任务来说,它的杀伤力太大了,因此我认为性能方面的考虑因素将在微优化下进行,如果OP需要捕捉类似于基于如果是web页面或地理位置,那么我肯定会推荐regex用于该任务。您所做的没有错,看到不同的方法来做相同的事情是很好的。但是为什么
/-\d+$/
太过了?。作为一个函数,它只是
const formatLabel=label=>label.replace(/-\d+$/,“”)
就像我说的,你所做的没有错,但是说
不涉及正则表达式
,似乎有点奇怪,这有点像我说
不涉及数组
。:)@三元的代谢,有趣的用法。你认为一个简单的
if
会更简单、更明显吗?(赞成票)