Regex to replace a string containing variable - javascript

I'm new to regex. I got a prob here. I work with xpaths strings. I want to remove a particular element from xpath string if the element has id = myVar
Example:
/html/body/div[3]/div[20]/section[1]/p[5]/span[1][#id="var645932"]/span
I want to replace the /span[1][#id="var645932"]/ with just / if my variable value is equal to id value i.e var645932
I need to do it in javascript. all are strings. I prefer regex. if any regex experts are there Kindly help. am stuck here. is it possible to accomplish it without regex ??
Any help are highly appreciated :) TIA

Try this:
var input = '/html/body/div[3]/div[20]/section[1]/p[5]/span[1][#id="var645932"]/span';
var regex = /\w+\[\w+\]\[\#id="var645932"\]\//gi;
input = input.replace(regex, '');
console.log(input);
Example fiddle
This regex is designed to work even if the structure of the HTML changes, eg:
var input = '/html/body/div[3]/div[20]/section[1]/div[6][#id="var645932"]/span';
If you need to set the id in the regex programmatically, use this:
var regex = new RegExp('/\w+\[\w+\]\[\#id="' + id + '"\]\//', 'gi');

You can use below code -
var expr = '/html/body/div[3]/div[20]/section[1]/p[5]/span[1][#id="var645932"]/span';
var idVal = "var645932";
expr = expr.replace('span[1][#id="'+idVal+'"]/','');
DEMO

Well, you could do it in the following way
var id = "var645932";
var regx = new RegExp('/[^/]+?\\[#id="' + id + '"]/');
var str = '/html/body/div[3]/div[20]/section[1]/p[5]/span[1][#id="var645932"]/span';
console.log(str.replace(regx, "/"));

Related

jQuery Regex from String

I have the following Regex that comes from a data Attribute on an HTML Element:
/^$|^[0-9]{2}.[0-9]{4}$/g
When I (manually) do:
/^$|^[0-9]{2}.[0-9]{4}$/g.test('01.2012');
It works and returns true.
When I put the Regex in a Variable like so:
var inputRegex = $(this).attr('data-validation');
And do:
inputRegex.test(input);
I get:
inputRegex.test is not a function.
I know that this is because inputRegex is a String and String does not have a test function, but when I create a RegExp object (new RegExp($(this).attr('data-validation')) it breaks my Regular Expression by escaping:
/\/^$|^[0-9]{2}.[0-9]{4}$\/g/
How can I use the data-attribute value as a Regular Expression? Please note that I cannot do: var regex = new RegExp(string, 'g'); because the Regular Expression(s) come predefined from the attribute.
var pattern = '\d+';
var regExp = new RegExp(pattern, 'g');
'1234dasf13241234'.match(regExp)
is it what you need?
var pattern = $(this).attr('data-validation');;
var regExp = new RegExp(pattern, 'g');
regExp.test(input);
in your case
your problem is that you need to retrieve the regex pattern from a attribute of an element, but it is returning string, and you want the string value to be like inline on your javascript code, like declaring plainly a regex. If this is really what you want to achieve, the closest solution is to use eval function, see updated code below:
var stringreg = "var inputRegex =" + $("#test").attr('data-validation') + ";"
eval(stringreg);
inputRegex.test(input);
This could help
var validation = "/^$|^[0-9]{2}.[0-9]{4}$/g"; //$(this).attr('data-validation')
var startIndex = validation.indexOf('/')+1
var lastIndex = validation.lastIndexOf('/');
var pattern = validation.substring(startIndex,lastIndex);
var options = validation.substring(lastIndex+1);
var regExp = new RegExp(pattern, options);
regExp.test('01.2012');
// true

How to remove string from string until a specefic character using jquery

I want to remove the last parameter in the href of a specific tag using jquery
for example replace href="app/controller/action/05/04/2014"
by href="app/controller/action/05/04"
Try using the String.lastIndexOf() and String.substring() in this context to achieve what you want,
var xText ="app/controller/action/05/04/2014";
xText = xText.substring(0,xText.lastIndexOf('/'));
DEMO
if you know which value you need to change ,than you can use replace:
var str = "app/controller/action/05/04/2014";
var res = str.replace("2014","04");
or else you can use array and change / update last value in array:
var str = "app/controller/action/05/04/2014";
var res = str.split("/");
We can use a regular expression replace which will be the fastest, compared to substring/slice.
var hreftxt ="app/controller/action/05/04/2014";
hreftxt = hreftxt.replace(/\/[^\/]*$/,"");

how to get numbers from a string in javascript?

I have
"id": 1468306
inside of a string, how can I use regular expression to get the number 1468306 for it?
You can use this regex:
/: (\d+)/
as in:
s = '"id": 1468306';
r = /: (\d+)/;
console.log(r.exec(s)[1]);
Output:
1468306
you can use parseInt() method in javascript as follows:
var str = parseInt(id);
Following code may help you:
var input = '"id": 1468306';
var matches = input.match(/"id": (\d+)/);
var id = matches[1];
The id get the required number.
JSON.parse("{" + yourString + "}").id
Will be your number if you have that in a String.
Fiddle: http://jsfiddle.net/SfeMh/
var regEx = /\d+/g;
var str = '"id": 1468306';
var numbers = str.match(regEx);
alert(numbers); // returns 1468306
It looks like you're trying to parse a JSON String. Try this way as already mentioned:
var parsedObj = JSON.parse(myJSONString);
alert(parsedObj.id); // returns 1468306
This will match in this cases
id : 156454;
id :156454;
id:156454;
/id\s?[:]\s?[0-9]+/g.match(stringhere)
Alright, my JSON answer still stands, use it if that's your full string you're giving us in the question. But if you really want a regex, here's one that will search for "id" and then find the number after.
parseInt(yourString.match(/("id"\s?:\s?)(\d+)/)[2])
Fiddle: http://jsfiddle.net/tS9M4/

How Can I Use This Regex With JavaScript

I have a regex and using it in PHP:
(?i)\b((?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z])(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))
I want it to use with javascript like:
regexp = new Regexep("here that regular expression");
and check with:
regexp.text(data)
But I couldn't do it work.
Please help me
Thanks,
var matches = data.match(/(?i)\b((?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z])(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))/);
or
var regex = /(?i)\b((?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z])(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))/;
var matches = regex.test(data);

Remove everything after a certain character

Is there a way to remove everything after a certain character or just choose everything up to that character? I'm getting the value from an href and up to the "?", and it's always going to be a different amount of characters.
Like this
/Controller/Action?id=11112&value=4444
I want the href to be /Controller/Action only, so I want to remove everything after the "?".
I'm using this now:
$('.Delete').click(function (e) {
e.preventDefault();
var id = $(this).parents('tr:first').attr('id');
var url = $(this).attr('href');
console.log(url);
}
You can also use the split() function. This seems to be the easiest one that comes to my mind :).
url.split('?')[0]
jsFiddle Demo
One advantage is this method will work even if there is no ? in the string - it will return the whole string.
var s = '/Controller/Action?id=11112&value=4444';
s = s.substring(0, s.indexOf('?'));
document.write(s);
Sample here
I should also mention that native string functions are much faster than regular expressions, which should only really be used when necessary (this isn't one of those cases).
Updated code to account for no '?':
var s = '/Controller/Action';
var n = s.indexOf('?');
s = s.substring(0, n != -1 ? n : s.length);
document.write(s);
Sample here
var href = "/Controller/Action?id=11112&value=4444";
href = href.replace(/\?.*/,'');
href ; //# => /Controller/Action
This will work if it finds a '?' and if it doesn't
May be very late party :p
You can use a back reference $'
$' - Inserts the portion of the string that follows the matched substring.
let str = "/Controller/Action?id=11112&value=4444"
let output = str.replace(/\?.*/g,"$'")
console.log(output)
It works for me very nicely:
var x = '/Controller/Action?id=11112&value=4444';
var remove_after= x.indexOf('?');
var result = x.substring(0, remove_after);
alert(result);
If you also want to keep "?" and just remove everything after that particular character, you can do:
var str = "/Controller/Action?id=11112&value=4444",
stripped = str.substring(0, str.indexOf('?') + '?'.length);
// output: /Controller/Action?
You can also use the split() method which, to me, is the easiest method for achieving this goal.
For example:
let dummyString ="Hello Javascript: This is dummy string"
dummyString = dummyString.split(':')[0]
console.log(dummyString)
// Returns "Hello Javascript"
Source: https://thispointer.com/javascript-remove-everything-after-a-certain-character/
if you add some json syringified objects, then you need to trim the spaces too... so i add the trim() too.
let x = "/Controller/Action?id=11112&value=4444";
let result = x.trim().substring(0, x.trim().indexOf('?'));
Worked for me:
var first = regexLabelOut.replace(/,.*/g, "");
It can easly be done using JavaScript for reference see link
JS String
EDIT
it can easly done as. ;)
var url="/Controller/Action?id=11112&value=4444 ";
var parameter_Start_index=url.indexOf('?');
var action_URL = url.substring(0, parameter_Start_index);
alert('action_URL : '+action_URL);

Categories