如何通过javascript或jquery从句子中提取括号内外的文本 [英] How to extract text which are outside and inside a bracket from a sentence through javascript or jquery

查看:106
本文介绍了如何通过javascript或jquery从句子中提取括号内外的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个句子存储在变量中.我需要将该句子提取成我的代码中其他3个变量中提到的3个部分,现在我已经对该变量进行了硬编码.然后,我需要分别控制台这些变量.我已经尝试过使用slice作为第一个变量,有没有更好的方法.这是下面的代码.任何人都可以帮助我.

I have a sentence stored in a variable.That sentence I need to extract into 3 parts which I have mentioned in other 3 variable in my code,for now I have hard coded in the variable. Then I need to console those variable separately.I have already tried with slice for first one,is there any better way to do it.Here is the code below.Can anyone please help me.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

脚本

$(document).ready(function(){
 var maintext = "Welcome to project,are you (1. Existing user or 2. new user)"  ;
 var text_split1 = maintext.split(' ').slice(0,4).join(' ');
//var text_split1 =  "Welcome to project,are you" ; /*this text should come from maintext after extraction*/
var text_split2 = "1. Existing user" ; /*this text should come from maintext after extraction*/
var text_split3 = "2. new user" ; /*this text should come from maintext after extraction*/
console.log(text_split1);
console.log(text_split2);
console.log(text_split3);
});

推荐答案

在这种情况下,最好的选择是创建一个正则表达式.

The best option in this case is to create a regular expression.

在您的情况下(如果我理解正确的话),您的句子包含:

In your case (if I got it right) you have a sentence consisting of:

  1. 一些文字
  2. 左括号'('
  3. 更多文字
  4. 或"一词
  5. 更多文字
  6. 右括号')'

因此,您希望正则表达式与上面的格式匹配,并希望捕获项1、3和5.

So you want a regex to match the format above and you want to capture the items 1, 3 and 5.

在这里,我为您制作了正则表达式:/^(.*) ?\((.*) or (.*)\)$/

Here, I made the regex for you: /^(.*) ?\((.*) or (.*)\)$/

现在,使用功能exec(string),您可以匹配所需的字符串并从中捕获所需的部分.

Now, using the function exec(string) you can match the desired string and capture the desired sections from it.

regex = /^(.*) ?\((.*) or (.*)\)$/;
maintext = "Welcome to project,are you (1. Existing user or 2. new user)";
matches = regex.exec(maintext);
text_split1 = matches[1];
text_split2 = matches[2];
text_split3 = matches[3];

请注意,我没有使用matches[0].这是因为这是正则表达式的完整匹配,在这种情况下,它将是您最初使用的完整字符串.

Notice that I didn't use matches[0]. That's because this is the full match from the regex, which, in this case, would be the full string you had at first.

此外,请注意,正则表达式可能会失败,括号内的任何文本都包含完整的单词或",该单词用于分隔字符串的两个部分.您必须确保不会发生这种情况,或者使用一些特殊字符将两个文本而不是单词分开.

Also, notice that the regex may fail with any of the texts inside the parenthesis contain the full word 'or', which is being used to separate the two portions of the string. You must secure this won't happen, or maybe use some special character to separate the two texts instead of the word.

这篇关于如何通过javascript或jquery从句子中提取括号内外的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆