Cutting HTML strings without breaking HTML tags

前端 未结 7 812
别跟我提以往
别跟我提以往 2021-01-04 19:34

How to write a function that can cut a string with HTML tags to an N-length string without breaking HTML tags while doing it.

The returned string doesn\'t need to b

7条回答
  •  臣服心动
    2021-01-04 19:50

    This might be overkill, but try looking up AWK, it can do this kind of things pretty easily since it's centered around processing text.

    You can also write a custom parsing script like

    string s = "Visit Croatia this summer."
    
    result = ""
    
    slice_limit = 9
    
    i= 0
    
    j = 0
    
    in_tag = false
    
    while i < slice_limit and j < s.size do
    
      if s[j] == "<" then in_tag = true
    
      if in_tag and s[i]==">" then in_tag = false
    
      if !in_tag then i++
    
      result += s[j]
    
    end
    

    ... or something like that (haven't tested, but it gives you the idea).

    EDIT: You will also have to add something to detect if the tag is closed or not (just add a flag like in_tag and mix it with some regular expression and it should work) Hope that helps

    EDIT2: if you gave the language you want to use, that could be helpful. javascript?

提交回复
热议问题