Home > Blockchain >  Replace text on lines containing certain character
Replace text on lines containing certain character

Time:08-29

    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  type="button" value="Convert" onclick="html2entities(this.form.data1)" onm ouseout="this.className='tec2'" onm ouseover="this.className='tec2 tec2hov'"><br />
<input  type="reset" value="Clear" onm ouseout="this.className='tec2'" onm ouseover="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)

CodePudding user response:

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  type="button" value="Convert" onclick="html2entities(this.form.data1)" onm ouseout="this.className='tec2'" onm ouseover="this.className='tec2 tec2hov'"><br />
  <input  type="reset" value="Clear" onm ouseout="this.className='tec2'" onm ouseover="this.className='tec2 tec2hov'"><br />
</form>

CodePudding user response:

You can try the following:

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

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

function html2entities(textarea) {
  const replacementPattern = /[(<>"'&]/g;
  const lines = textarea.value.split('\n');
  const buffer = [];
  for (const line of lines) {
    let replacedLine = line;
    if (!!line) { // ignore empty lines
      if (shouldReplace(line)) {
        replacedLine = line.replaceAll(replacementPattern, (it) => replacechar(it));
      }
      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  type="button" value="Convert" onclick="html2entities(this.form.data1)" onm ouseout="this.className='tec2'" onm ouseover="this.className='tec2 tec2hov'"><br />
  <input  type="reset" value="Clear" onm ouseout="this.className='tec2'" onm ouseover="this.className='tec2 tec2hov'">
  <br />
</form>

CodePudding user response:

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;"
]

CodePudding user response:

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.

  • Related