如何从具有条件的字符串中删除文本 [英] How to remove text from a string with a condition
本文介绍了如何从具有条件的字符串中删除文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
var string ='Good-Location1'
考虑来自db的'Goods-Location1'
我要在' - '之后删除所有文本
var string='Good-Location1'
consider 'Goods-Location1' from db
I want remove all the text after '-'
推荐答案
使用此
Use this
var s = 'Good-Location1';
s = s.substring(0, s.indexOf('-'));
参考: http://stackoverflow.com/a / 5631434/2645738 [ ^ ]
问候..
Reference : http://stackoverflow.com/a/5631434/2645738[^]
Regards..
您可以使用正则表达式,例如:
You can use regular expressions, for example:
input = 'Good-Location1';
result = input.replace(/-.*/, "");
// if you need to preserve '-' (you mentioned "after '-'")
// you can change it to:
differentResult = input.replace(/-.*/, "-");
这个替换取代了从' - '到字符串结尾的所有内容,或者在' - '之后到字符串结尾的所有内容。如果您学习正则表达式,则可以进行各种匹配和替换。例如,请参阅:
https://developer.mozilla .org / zh-CN / docs / Web / JavaScript / Guide / Regular_Expressions [ ^ ],
http ://www.regular-expressions.info/javascript.html [ ^ ]。
这篇关于如何从具有条件的字符串中删除文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文