【问题标题】:Javascript - How to find a sub-string in a string and check if there's a space before/after it?Javascript - 如何在字符串中查找子字符串并检查它之前/之后是否有空格?
【发布时间】:2012-05-16 19:55:33
【问题描述】:
有谁知道我如何在字符串中找到子字符串"<br/>" 并检查它之前或之后是否有空格?我一直在使用它来检查字符串是否包含子字符串:
if (str.indexOf('<br/>') !== -1) {
}
但是我将如何检查它之前或之后的空间?感谢您的帮助!
【问题讨论】:
标签:
javascript
string
contains
indexof
【解决方案1】:
var idx = str.indexOf('<br/>');
var hasSpaces = idx > 0 &&
(str.charAt(idx -1) === ' ' || str.charAt(idx + 5) === ' ');
编辑:如果您也关心<br/> 的索引,即使没有空格,此解决方案也有效。如果您在没有空格的情况下不关心<br/>,那么@David 的解决方案会更好(尽管请注意\b 匹配任何单词边界,因此您可能希望根据您的需要使其更严格)。
另一个编辑:我刚刚意识到提供的几个正则表达式解决方案只有在前后有空格的情况下才有效。下面是一个示例,可以在 before 或 after 或 两边 使用空格:
var match = str.match(/\s?<br\/>\s?/);
var hasSpaces = match && match[0].length > 5;
【解决方案2】:
var index = str.indexOf('<br/>');
var spaceBefore = false;
var spaceAfter = false;
if (index !== -1) {
if (str.charAt(index - 1) === ' ') {
spaceBefore = true;
}
if (str.charAt(index + 5) === ' ') {
spaceAfter = true;
}
}
http://jsfiddle.net/jbabey/8FYhv/