【问题标题】: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) === ' ');

编辑:如果您也关心&lt;br/&gt; 的索引,即使没有空格,此解决方案也有效。如果您在没有空格的情况下不关心&lt;br/&gt;,那么@David 的解决方案会更好(尽管请注意\b 匹配任何单词边界,因此您可能希望根据您的需要使其更严格)。


另一个编辑:我刚刚意识到提供的几个正则表达式解决方案只有在前后有空格的情况下才有效。下面是一个示例,可以在 beforeafter两边 使用空格:

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/

    【讨论】:

      猜你喜欢
      • 2012-02-10
      • 1970-01-01
      • 2015-03-22
      • 1970-01-01
      • 2017-05-04
      • 1970-01-01
      • 2022-06-25
      • 2010-12-16
      相关资源
      最近更新 更多