我有一句话“欢迎来到一个项目,你是一个”,在这里我需要删除“ a”,该句子仅在句子包含最后一个字母为“ a”时才删除,否则我在下面的代码中尝试过此代码,但在我的项目中不起作用。
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="messages"></ul>
var text = 'Welcome to project, are you a (1. new user one, 2. test user two, 3. minor Accident one or 4. Major Accident)';
var regex = /\((.*)\)/;
var m;
m = regex.exec(text);
console.log(m[1]);
// 1. new user one, 2. test user two, 3. minor Accident one or 4. Major Accident
var list = m[1];
var items = list.split(/([\d]. )/g);
var message = $('.messages');
var introText = text.split('(');
var test = introText[0]
alert(test.replace(/\a$/, ""));
答案 0 :(得分:1)
您可以使用正则表达式轻松完成此操作:
var s = "Welcome to project are you a";
let t = s.replace(/\a$/,"")
console.log(t) // --> Welcome to project are you
var s = "Welcome to project are you x";
let t = s.replace(/\a$/,"")
console.log(t) // --> Welcome to project are you x
请注意,.$
将匹配字符串末尾的任何字符,因此a$
将匹配字符串末尾的字符'a'。