askquestionzero askquestionzero - 4 months ago 11
Javascript Question

javascript: can someone explain the code

i ask a question yesterday. how to remove the tag name only, and remove the tag name including the content yesterday using jquery.

and the answer is using regex.

can someone explain the code below for me just the regex part?

i already read some articles about regex but i think i dont fully understand it clearly.

if possible, i want to convert it to c# code, but i can't do it yet because i dont fully understand the code. thank you

first code

$(function() {
function removeNode(str, nodeName) {
var pattern = '<'+nodeName+'>[\\s\\w]+<\/'+nodeName+'>';
var regex = new RegExp(pattern, 'gi');
return str.replace(regex, '').replace(/^\s*[\r\n]/gm, '');
}


what i dont undertand in the first code is where does the 'gi' come from?
and the return

var regex = new RegExp(pattern, 'gi');
return str.replace(regex, '').replace(/^\s*[\r\n]/gm, '');


second code

$(function() {
function removeNodeButRetain(str, nodeName) {
var pattern = '<\/?'+nodeName+'>';
var regex = new RegExp(pattern, 'gi');
return str.replace(regex, '').replace(/^\s*[\r\n]/gm, '');
}

what i dont understand is the

var regex = new RegExp(pattern, 'gi');
return str.replace(regex, '').replace(/^\s*[\r\n]/gm, '');


third code

jQuery(document).ready(function(){
textval = $('textarea').val();
textnewval = textval.replace('Para TextBreak="No"', 'p').replace('/Para', '/p');

if(textnewval.indexOf('Italic') >= 0) //If Italic
{
EmphasisAttr = 'Italic';
textnewval = textnewval.replace('Emphasis Type="'+EmphasisAttr+'"', 'i').replace('/Emphasis', '/i');
}
if(textnewval.indexOf('Bold') >= 0) //If Bold
{
EmphasisAttr = 'Bold';
textnewval = textnewval.replace('Emphasis Type="'+EmphasisAttr+'"', 'b').replace('/Emphasis', '/b');
}
if(textnewval.indexOf('Underline') >= 0) //If underline
{
EmphasisAttr = 'Underline';
textnewval = textnewval.replace('Emphasis Type="'+EmphasisAttr+'"', 'u').replace('/Emphasis', '/u');
}


$('textarea').val(textnewval);
alert($('textarea').val());
});

Answer

The regex: http://regexr.com/3dr56

Will match any nodes that consist of say the following:

<div>hello world</div>

Provided that the parameters passed to the function:

function removeNode(str, nodeName) {
   var pattern = '<'+nodeName+'>[\\s\\w]+<\/'+nodeName+'>';
   var regex = new RegExp(pattern, 'gi');
   return str.replace(regex, '').replace(/^\s*[\r\n]/gm, '');
}
console.log("Node: <div>hello world</div>");
console.log("String returned: " + removeNode("hello world", "div"));

are:

Node match: <div>hello world</div>

removeNode("hello world", "div"); will return:

hello world

The function itself will return the string within the node.

More info can be found here about Regular Expressions.

Comments