[英]Remove HTML Tags and whitespace from string using regex javascript
[英]JavaScript Regex - Remove Whitespace from Start and End
我在下面的挑战中工作了大约 3 个小时,但我的代码都没有工作。 决定查看解决方案以了解为什么我不工作。 当我查看解决方案时,我很困惑,因为我认为 \\s 来识别空格而不是删除它们......有人可以帮我解释为什么使用 \\s 而不是 \\S 以及为什么使用空字符串 ( "") 去掉两端的空格。
挑战
编写一个正则表达式并使用适当的字符串方法去除字符串开头和结尾的空格。
//SOLUTION
let hello = " Hello, World! ";
let wsRegex = /^\s+|\s+$/g;
let result = hello.replace(wsRegex, "");
replace
的第二个参数是您将从第一个参数的匹配项中替换的内容。
正则表达式将匹配/选择字符串开头 (^) 和结尾 ($) 的空格,然后将替换为 ""。
当您使用正则表达式/(\\S)/g
您将匹配除空格之外的所有内容,在这种情况下,您将使用hello.replace(/(\\S)/g, '$1')
;
$1
表示正则表达式的第一组。
\\s
表示正则表达式中的空白字符,例如 <space>、<tab> 等。^
表示字符串的开头$
表示字符串的结尾|
表示 OR(匹配左侧或右侧)+
表示 1 个或更多(基于左侧的规则)/a regex/g
g
表示“全局”,也就是“多次匹配”,因为您可能需要在开头和结尾进行匹配所以正则表达式的意思是:
/^\s+|\s+$/g
/ / Wrap the regex (how you do it in JS)
^\s+ Try to match at the beginning one or more whitespace chars
| Or...
\s+$ Try to match whitespace chars at the end
g Match as many times as you can
String.prototype.replace用作为第二个参数提供的字符串替换在正则表达式中找到的匹配项,在本例中为空字符串。
所以内部流程是:
""
替换每个匹配项,完全删除这些匹配项 let hello = " Hello, World! "; let wsRegex = /^\\s+|\\s+$/g; let result = hello.replace(wsRegex, ""); console.log('"' + result + '"');
大多数人在使用全局标志时使用String.prototype.replaceAll而不是.replace
(
let hello = " Hello, World! "; let wsRegex = /^\\s+|\\s+$/g; let result = hello.replaceAll(wsRegex, ""); console.log('"' + result + '"');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.