简体   繁体   English

尝试在JavaScript中修剪字符串的一部分

[英]Trying to trim part of a string in JavaScript

I am having a hard time figuring out how to trim part of a string in JavaScript. 我很难弄清楚如何在JavaScript中修剪字符串的一部分。 I need to remove inconsistencies since they are coming from a DB. 我需要消除不一致之处,因为它们来自数据库。 Hoping someone can help me with this. 希望有人可以帮助我。

On my web page I have some occurences of 2 tbsp (33 g) and 2 tbsp (33g) . 在我的网页上,我发生了2汤匙(33克)2汤匙(33克)的情况

I need to get everything to look like this 2 tbsp (33g) . 我需要使所有东西看起来像这样2汤匙(33克) So basically anything between the parenthesis, the whitespace needs to be removed. 因此,基本上在括号之间的所有内容都需要删除空格。 How can I achieve this with JS? 如何用JS实现呢?

Here is my code: $(".servingSize").html(servingSize.replace(" ", "")); 这是我的代码: $(".servingSize").html(servingSize.replace(" ", ""));

This only removes the white space before the parenthesis. 这只会删除括号前的空白。 Not sure what I am doing wrong. 不知道我在做什么错。

With the replace method, the only way to replace all occurrences of a match in a string is with a regex argument. 使用replace方法,替换字符串中所有匹配项的唯一方法是使用regex参数。 The proper way to do this would be replace(/\\s/g, '') . 正确的方法是replace(/\\s/g, '') \\s is a special argument in regexes that matches all whitespace characters. \\s是正则表达式中的一个特殊参数,它匹配所有空白字符。

In your case, replacing the characters only within the parentheses, you could use this regex: servingSize.replace(/\\s+(?=g)/g, '') . 在您的情况下,仅替换括号内的字符,可以使用此正则表达式: servingSize.replace(/\\s+(?=g)/g, '') The (?=g) is a positive lookahead, which only selects runs of whitespace with the g character following it. (?=g)是一个正向超前,仅选择空白行,其后跟g字符。

furkle definitely got the right answer, but I'm going to post up an alternative solution that handles cases where you don't know what units are inside the parentheses. Furkle肯定找到了正确的答案,但是我将发布一种替代解决方案,用于处理您不知道括号内包含哪些单位的情况。

var regexPattern= /^([^\(]*\([^ ]*)( )([^\)]*\).*)$/;

while (regexPattern.test(servingSize)) {
    servingSize = servingSize.replace(regexPattern, "$1$3");
}

$(".servingSize").html(servingSize);

The pattern breaks down like this: 模式分解如下:

/^ - start at the beginning of the string /^ -从字符串的开头开始

([^\\(]*\\([^ ]*) - capture all characters up until the opening parenthesis, the parenthesis itself, and any non-space characters that immediately follow it ([^\\(]*\\([^ ]*) -捕获所有字符,直到右括号,括号本身以及紧随其后的所有非空格字符

( ) - capture the first space character inside the parentheses ( ) -捕获括号内的第一个空格字符

([^\\)]*\\).*) - capture all characters up until the closing parenthesis, the parenthesis itself, and any characters that follow it ([^\\)]*\\).*) -捕获所有字符,直到右括号,括号本身以及其后的所有字符

$/ - go all the way to the end of the string $/ -一直到字符串的结尾

By checking it with the .test() method in the while loop, it will run the loop as long as it still finds a space inside the parentheses. 通过在while循环中使用.test()方法对其进行检查,只要仍在括号内找到一个空格,它将运行该循环。 If it runs, it will replace the entire string with all of the characters up until the matched space and all of the characters after it. 如果运行,它将用所有字符替换整个字符串,直到匹配的空格和其后的所有字符为止。

Once the loop finds no more spaces, it quits and updates the HTML. 一旦循环找不到更多空间,它将退出并更新HTML。

By doing it this way, the code works for any units that you might use: 通过这种方式,代码可用于您可能使用的任何单位:

  • "2 tbsp (33 g)" ===> "2 tbsp (33g)" “ 2汤匙(33克)” ===>“ 2汤匙(33克)”
  • "1 hour (360 sec)" ===> "1 hour (360sec)" “ 1小时(360秒)” ===>“ 1小时(360秒)”
  • "1 ton (2000 lbs)" ===> "1 ton (2000lbs)" “ 1吨(2000磅)” ===>“ 1吨(2000磅)”

Additionally, this will even handle extreme examples, such as: 此外,这甚至可以处理一些极端的示例,例如:

  • "2 tbsp ( 3 3 g )" ===> "2 tbsp (33g)" “ 2汤匙(3 3克)” ===>“ 2汤匙(33克)”

Another way to do this is to replace the pattern: 执行此操作的另一种方法是替换模式:

servingSize.replace(/\((\s*)(\d+)(\s*)(\w+)(\s*)\)/g, '($2$4)');

Assuming the pattern is always a bracket ( followed by a number, followed by one or more letters, and another bracket ) , we can match any surrounding space and just not include those groups in the replacement. 假设模式始终是一个括号(后跟一个数字,然后是一个或多个字母,再加上一个括号) ,则我们可以匹配任何周围的空间,而不必在替换中包括这些组。 This works for any other unit as well. 这也适用于其他任何单位。

If you are searching and replacing a whole HTML page, I would further lock it down to be more specific, just to be safe: 如果要搜索和替换整个HTML页面,为了安全起见,我会进一步将其锁定为更具体:

servingSize.replace(/(\d+ (?:tbsp|tsp))\s\((\s*)(\d+)(\s*)(\w+)(\s*)\)/g, '$1 ($3$5)');

(though if you are using jquery to match specific elements, the first one should be fine) (尽管如果您使用jQuery来匹配特定元素,则第一个应该没问题)

Anything between ( and ) in a regex marks a group, which can be accessed by index using $ followed by the group number (0 is the whole regex matched string, 1 starts the first group captured). 正则表达式中()之间的任何内容都标记了一个组,可以通过索引使用$加上组号来访问该组(0是整个正则表达式匹配的字符串,1开始捕获的第一个组)。 In the str.Replace({regex}, s) format, the s string can contain these ${#} tokens. str.Replace({regex}, s)格式中, s字符串可以包含这些${#}标记。

Note: This will handle any spaces around the matched items: 注意:这将处理匹配项周围的所有空格:

2 tbsp ( 33 g ) => 2 tbsp (33g) 2 tbsp ( 33 g ) => 2 tbsp (33g)

even other units instead of 'g' if needed in the future. 如果将来需要,甚至可以用其他单位代替“ g”。

use $(".servingSize").html(servingSize.replace(" g", "g")); 使用$(“。servingSize”)。html(servingSize.replace(“ g”,“ g”)); This will replace only the space before grams, not every space 这将仅替换克之前的空格,而不是每个空格

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM