0

    function html2entities() {
        var a = /[(<>"'&]/g;
        for (i = 0; i < arguments.length; i++) arguments[i].value = arguments[i].value.replace(a, function(a) {
            return replacechar(a)
        })
    }

function replacechar(a) {
    if ("<" == a) return "&lt;";
    if (">" == a) return "&gt;";
    if ('"' == a) return "&quot;";
    if ("'" == a) return "&#039;";
    if ("&" == a) return "&amp;"
};
<form><textarea name="data1" style="width: 590px; height: 200px"></textarea><br />
<input class="tec2" type="button" value="Convert" onclick="html2entities(this.form.data1)" onmouseout="this.className='tec2'" onmouseover="this.className='tec2 tec2hov'"><br />
<input class="tec2" type="reset" value="Clear" onmouseout="this.className='tec2'" onmouseover="this.className='tec2 tec2hov'"><br />
</form><br />

Hello, i have this code, but i need it to execute only on lines containing a certain number, for example "3". How can i do this? It probably needs some regex but i'm not much of coder :(

l.e. Sorry for not providing full code and all the details from the start I've made a snippet with the whole code.

What i need is when i enter a text like this:

3-c-<text>
ff4-"text"
6--&text&
aa3---"text"

to be converted intro:

3-c-&lt;text&gt;
ff4-"text"
6--&text&
aa3---&quot;text&quot;

(I would need to expand the code, to make it work with lines containing different numbers than 3, and other characters to be replaced, but i think i can do this on my own afterwards)

FuZzy1
  • 77
  • 1
  • 10

4 Answers4

1

You can use the String.includes() method to find out if the line contains the number "3" or not

function html2entities(input) {
    var a = /[(<>"'&]/g;

    // split string to individual lines
    var lines = input.value.split("\n");
    
    for (i = 0; i < lines.length; i++) {
        // if the line value does not contain "3". continue to the next line
        if (!lines[i].includes("3")) continue;

        lines[i] = lines[i].replace(a, function(a) {
            return replacechar(a)
        });
    }

    // recombine the lines
    var output = lines.join("\n");
    
    // test
    console.log(output);
    alert(output);
    
    return output;
}

function replacechar(a) {
    if ("<" == a) return "&lt;";
    if (">" == a) return "&gt;";
    if ('"' == a) return "&quot;";
    if ("'" == a) return "&#039;";
    if ("&" == a) return "&amp;"
}
<form>
  <textarea name="data1" style="width: 590px; height: 200px"></textarea><br />
  <input class="tec2" type="button" value="Convert" onclick="html2entities(this.form.data1)" onmouseout="this.className='tec2'" onmouseover="this.className='tec2 tec2hov'"><br />
  <input class="tec2" type="reset" value="Clear" onmouseout="this.className='tec2'" onmouseover="this.className='tec2 tec2hov'"><br />
</form>
mcanam
  • 26
  • 5
  • thanks for the answer, i've tried it but it doesn't seem to work, the replacements happen everywhere. I updated the first post with more details and the complete code that i have, hope it makes more clear now what i'm trying to do – FuZzy1 Aug 28 '22 at 10:13
  • Thanks a lot! , this seems to work just fine, and i also managed to edit it with the changes i need. But i have one problem, the output text is displayed in a pop-up window, i want it to be updated in the text area box, as in the original code, so i can copy it (also maybe you could add a extra "Copy Result" button, if it's not too much trouble to do) – FuZzy1 Aug 28 '22 at 16:26
  • to display the output in textarea maybe you can take the code snippet from @F. Müller answer. and I found a good answer to copy text to clipboard. please check [this answer](https://stackoverflow.com/a/7218068/15401038) – mcanam Aug 28 '22 at 19:06
1

You can try the following:

const replacementTokens = ['3', '6']; // whatever you want to check here

function shouldReplace(line) {
  for (const token of replacementTokens) {
    if (line.startsWith(token)) { // this could also be a regex or something else
      return true;
    }
  }
  return false;
}

function html2entities(textarea) {
  const replacementPattern = /[(<>"'&]/g;
  const lines = textarea.value.split('\n');
  const buffer = [];
  for (const line of lines) {
    let replacedLine = line;
    if (shouldReplace(line)) {
      replacedLine = line.replaceAll(replacementPattern, replacechar);
    }
    buffer.push(replacedLine);
  }
  console.log('buffer:', buffer);
  textarea.value = buffer.join('\n');
}

function replacechar(a) {
  if ("<" == a) return "&lt;";
  if (">" == a) return "&gt;";
  if ('"' == a) return "&quot;";
  if ("'" == a) return "&#039;";
  if ("&" == a) return "&amp;";
}
<form>
  <textarea name="data1" style="width: 590px; height: 200px"></textarea>
  <br />
  <input class="tec2" type="button" value="Convert" onclick="html2entities(this.form.data1)" onmouseout="this.className='tec2'" onmouseover="this.className='tec2 tec2hov'"><br />
  <input class="tec2" type="reset" value="Clear" onmouseout="this.className='tec2'" onmouseover="this.className='tec2 tec2hov'">
  <br />
</form>
F. Müller
  • 3,969
  • 8
  • 38
  • 49
0

My try for this. Hope this helps.

function escape(str) {
    return str
        // replace & at first so that does not mess up other escapes
        .replaceAll("&", "&amp;")
        .replaceAll("<", "&lt;")
        .replaceAll(">", "&gt;")
        .replaceAll("\"", "&quot;")
        .replaceAll("'", "&#39;")
}
const lines = [
    '3-c-<text>',
    'ff4-"text"',
    '6--&text&',
    'aa3---"text"'
]

let result = []

lines.forEach(line => {
    result.push(escape(line))
})

console.log(result)

Result

[
    "3-c-&lt;text&gt;",
    "ff4-&quot;text&quot;",
    "6--&amp;text&amp;",
    "aa3---&quot;text&quot;"
]
Kiran Parajuli
  • 820
  • 6
  • 14
-2

You can try something like this. I have added only two, you can keep adding more as you much you want

var htmlStr = "<p>This is paragraph element. </p>"
var rendered_htmlStr = htmlStr.replaceAll("<","&lt;").replaceAll(">","&gt;");

console.log(rendered_htmlStr);

Here is more dynamic way,

let replacers = ["&lt;","&gt;","&quot;","&#039;","&amp; "]
let symbls = ["<",">",'"',"'","& "];

let str = "<p>This is paragraph element. </p>";
let renderd_str = "";
for(let i = 0; i < symbls.length; i++){
    if(str.indexOf(symbls[i]) > -1){
        str = str.replaceAll(symbls[i], replacers[i]);
    }
}

console.log('renderd_str', str)

I did a trick here, see in &lt; we have this "&", if we run the loop, in next iteration it will try to replace & from &lt; with &amp; which will return incorrect result.

So the trick is to add a space after & in symbls array and also add space after &amp in replacers array. As I have provided in both of the arrays.

I hope this will work. Whichever way you want.

Thanks.

Subhajit Das
  • 399
  • 7
  • 19
  • Fails to answer the question (limiting the RegEx to lines that don't contain a character). Also using a dict. is the cleanest way to go here. – Luatic Aug 28 '22 at 09:43
  • *"I did a trick here,"*: first this does not answer the question, but worse, this "trick" is not working when `&` is **not** followed by a space, like in `&1`. – trincot Aug 28 '22 at 09:46
  • yes, the main thing i need is missing, i've updated the post with more details of what i want to do – FuZzy1 Aug 28 '22 at 10:12
  • second part was optional, anyway with first option it solves the issue – Subhajit Das Aug 28 '22 at 11:25