How to find a string outside a string using javascript regex?

Viewed 421

I'm trying to get any string which is not between two string characters(any string outside two string characters).

I have tried the code below but it keeps giving me 'undefined'.

var string = "start<i>ignore text inside here</i>end"
var string = string.match(/[^<i>(.*)<\/i>]/);
console.log(string)

What I'm expecting to get here is 'start, end'. But when ever I run the code above I'm getting 'undefined' as a result.

3 Answers

This is a character class which means don't match any character <,>i,(,.,*,),/ it doesn't mean that it will avoid matching complete sentence

[^<i>(.*)</i>]

You can simply use split instead of match

var string = "start<i>ignore text inside here</i>end"
var string = string.split(/<i>.*<\/i>/g);

console.log(string)

It seems to me, you want to remove HTML tags and content inside tags,

in that case, you can use this code,

removeTags(string, array) {
        return array ? string.split("<").filter(function (val) { return f(array, val); }).map(function (val) { return f(array, val); }).join("") : string.split("<").map(function (d) { return d.split(">").pop(); }).join("");
        function f(array, value) {
            return array.map(function (d) { return value.includes(d + ">"); }).indexOf(true) != -1 ? "<" + value : value.split(">")[1];
        }
    }

Here, in removeTags method, a string is the string which you want to perform an operation on. and an array is the specific HTML tags that you want to remove, pass null if you want to remove all HTML tags.

*

Please let me know if you want to do something else than this. give an example likewise.

*

If your string is a single line of text (like in your example) you could use:

let str = "start<i>ignore text inside here</i>end";
str = str.match(/^([a-z]+)<.*?>.*?<.*?>([a-z]+)$/);
console.log(str[1], str[2]);

You could also replace the <.*?>.*?<.*?> with <.*?> and get the same result:

let str = "start<i>ignore text inside here</i>end";
str = str.match(/^([a-z]+)<.*?>([a-z]+)$/);
console.log(str[1], str[2]);

Either way, both snippets should output:

start end

Good luck.

Related