2

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.

Malekai
  • 4,765
  • 5
  • 25
  • 60
James
  • 120
  • 1
  • 7
  • are you trying to capture all characters between any gvien set of characters? Such as `` and ``? Because there's no such thing as a `string character` any character could be a string character. – Smytt Jun 20 '19 at 09:10
  • The pattern in the reqular expressionn has been turned into a character set by putting it between `[` and `]`. Try removing the square brackets and using `string.replace` to replace matches with an empty string. – traktor Jun 21 '19 at 01:35

3 Answers3

2

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)
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
0

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.

*

niranjan_harpale
  • 2,048
  • 1
  • 17
  • 21
0

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.

Malekai
  • 4,765
  • 5
  • 25
  • 60