0

Below is my text, in this regex should find the text/content not starting with [ that means its a shortcode.

[fullwidth blah="1"]
    text line lorem ipsuim blah blah
    [divider value="80"]

    another line with extra space above

    [text] this is test[/text]
         another line
[/fullwidth]

anything found in [fullwidth] that starts without bracket [ needs to be wrapped in [text]anything[/text]

so the final output will become

[fullwidth blah="1"]
    [text]text line lorem ipsuim blah blah[/text]
    [divider value="80"]    
    [text]another line with extra space above[/text]
    [text] this is test[/text]
    [text]another line[/text]
[/fullwidth]
Themer
  • 185
  • 1
  • 12

1 Answers1

0

You can filter out the line without leading [text] using regex

And add the shortcode back

var content = $('p').text(); //your text content
var content_per_line = content.split(/[\r\n]+/g);
//explain about this regex: http://stackoverflow.com/a/406408/1348494
var regex = /^((?!\[).)*$/g;
var output = '';

$.each(content_per_line, function(ind ,line) {
  var trimmed_line = $.trim(line);
  console.log(trimmed_line)
  if (trimmed_line !== '\n' && regex.test(trimmed_line) === true) {
    output += '[text]' + line + '[/text]';
  } else {
    output += line;
  }
  output += '<br>'
})

console.log(output)

Try this on JSFiddle

osk2
  • 329
  • 3
  • 9
  • Thanks Osk, it will definitely help me getting started, however I just tested the jsFiddle and it skips some lines, please have a look at this https://jsfiddle.net/82h14g7e/2/ – Themer Dec 12 '16 at 08:38
  • I update regex pattern, this should works https://jsfiddle.net/82h14g7e/3/ – osk2 Dec 12 '16 at 09:16
  • Thanks osk, it works fine now :) thanks a lot. One more thing, if you dont mind me helping, how can we check the code inside the [fullwidth] content [/fullwidth].. I am asking as no one answered my original question: http://stackoverflow.com/questions/41086728/search-text-and-replace-with-regex-indexof – Themer Dec 12 '16 at 09:46
  • Hi again OSK, I just got a chance to test it, however the newest code also includes empty lines and does not skip shortcode e.g. it should skip [anything var="asd"] any content many lines[/anything].. it keeps adding it to each and every line, please have a look at this: https://jsfiddle.net/82h14g7e/4/ – Themer Dec 12 '16 at 16:11