简体   繁体   中英

Javascript - How to find a sub-string in a string and check if there's a space before/after it?

Does anyone know how I can find the sub-string "<br/>" in a string and check if there's a space before or after it? I've been using this to check if the string contains the sub-string:

if (str.indexOf('<br/>') !== -1) {
}

But how would I go about checking before or after it for a space? Thanks for the help!

var idx = str.indexOf('<br/>');

var hasSpaces = idx > 0 &&
    (str.charAt(idx -1) === ' ' || str.charAt(idx + 5) === ' ');

Edit: this solution works if you also care about the index of of the <br/> even when there are no spaces. If you don't care about the <br/> when there are no spaces, then @David's solution is better (although note that \\b matches any word boundary, so you may want to make it stricter, depending on your needs).


Another edit: I just realized several of the regex solutions offered will only work if there is a space before AND after. Here's an example that will work with a space before or after or on both sides :

var match = str.match(/\s?<br\/>\s?/);
var hasSpaces = match && match[0].length > 5;
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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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