multiple occurence in a string - javascript

I have a string in which I want to replace an occurence which I am not being able to achieve following is the code
var code="user_1/has some text and user_1? also has some text";
newcode=code.replace(/user_1//g,'_');
One more thing if i have to replace a string from another string how to do?
example.
var replacestring="user_1";
var code="user_1/some value here for some user";
var newcode=code.replace(/+replacestring+/g,'_');

/ is a special char thus needs to be escaped with \ before it:
var code = "user_1/has some text and user_1? also has some text";
var newcode = code.replace(/user_1\//g, '_');
alert(newcode);​
Live DEMO
if you want to replace all user_1, use this:
var code = "user_1/has some text and user_1? also has some text";
var newcode = code.replace(/user_1/g, '_');
alert(newcode);​
Live DEMO

Escape the / in the regex using \
newcode=code.replace(/user_1\//g,'_');
For your comment
#Vega I have another confusion. can i use a value in a string to pass
instead of user_1/ for replacement? what would be the syntax?
You can initialize RegEx object like below,
var userName = 'user_1/';
var newcode = code.replace(new RegExp(userName, 'g'), '_');
Read More about RegEx

Related

Use multiple instructions in one RegExp(JS)

I have:
var myText = <"input">
I want to cut the string down to only input. Is possible to define a regular expression, which does this? I know how to get rid of the <"
myText = myText.replace(/<"/,g,'')
But what about the end of the line? Of course I could just write another regular expression, like this:
myText = myText.replace(/<"/,g,'').replace(/">/,g,'')
But I´m sure there is an easier way, right? :)
Use regexp that matches start or end of sequence
var myText = "<input>";
myText.replace(/^<"|">$/g, '')
Instead you can use .match() method:
var myText = "<input>";
console.log(myText.match(/[(a-z)]+/g)[0]);
You can do like this:
var myText = '<input>';
myText.replace(/<(.*)>/, '$1');
Or
myText.match(/<(.*)>/)[1]
You can use a character class [] to specify any of the present characters:
var myText = '<input>';
console.log(myText.replace(/[<>]/g, ''));
If you want to replace any non alphanumeric letters, you can do:
var myText = '<input>';
console.log(myText.replace(/[^a-zA-Z0-9]/g, ''));
var myText = "<input>";
console.log(myText.replace(/(^<)|(>$)/g, '');

Split a string of file input field

I need to grab a value from input field in a form, i need only the file name. The string looks like so:
var str = 'C:\Users\User\Desktop\file_name.ext';
If i try to run (yes, the backslash is escaped)
str.split(\\)[str.length-1]
It does not work, as the slashes in the string aren't escaped. Simple console.log(str) gives me C:UsersUserDesktopile_name.ext and you see where the problem is. How do i get around that?
'C:\Users\User\Desktop\file_name.ext'.split(/\\|//).pop();
Assume the backslashes are escaped. I'm confusing people by escaping my backslashes. The above string is "as is".
You need to escape the backslashes in your string:
"C:\\Users\\User\\Desktop\\file_name.ext".split("\\").pop();
var str = 'C:\\Users\\User\\Desktop\\file_name.ext';
var parts = str.split('\\');
var result = parts[parts.length - 1];
The solution, and link to fiddle fiddle
$(function () {
function getFileName(path) {
return path.match(/[-_\w]+[.][\w]+$/i)[0];
}
$('#data_up').change(function () {
var fileName = $(this).val();
$('#data').val('somepath/' + getFileName(fileName));
});
});

how to config RegExp when string contains parentheses

I'm sure this is an easy one, but I can't find it on the net.
This code:
var new_html = "foo and bar(arg)";
var bad_string = "bar(arg)";
var regex = new RegExp(bad_string, "igm");
var bad_start = new_html.search(regex);
sets bad_start to -1 (not found). If I remove the (arg), it runs as expected (bad_start == 8). Is there something I can do to make the (very handy) "new Regexp" syntax work, or do I have to find another way? This example is trivial, but in the real app it would be doing global search and replace, so I need the regex and the "g". Or do I?
TIA
Escape the brackets by double back slashes \\. Try this.
var new_html = "foo and bar(arg)";
var bad_string = "bar\\(arg\\)";
var regex = new RegExp(bad_string, "igm");
var bad_start = new_html.search(regex);
Demo
Your RegEx definition string should be:
var bad_string = "bar\\(arg\\)";
Special characters need to be escaped when using RegEx, and because you are building the RegEx in a string you need to escape your escape character :P
http://www.regular-expressions.info/characters.html
You need to escape the special characters contained in string you are creating your Regex from. For example, define this function:
function escapeRegex(string) {
return string.replace(/[/\-\\^$*+?.()|[\]{}]/g, '\\$&');
}
And use it to assign the result to your bad_string variable:
let bad_string = "bar(arg)"
bad_string = escapeRegex(bad_string)
// You can now use the string to create the Regex :v:

Javascript replace does not replace

The pattern in this code does not replace the parenthesis. I've also tried "/(|)/g".
var re = "/[^a-z]/g",
txt = navsel.options[i].text.split(" ")[0], // here I get the text from a select and I split it.
// What I expect is strings like "(en)" , "(el)" etc
txt = txt.replace(re," ")
Thanks in advance
Your regex is a string, this will try to replace that exact string. Regex objects don't have quotes around them, just the delimiters. Try it like this:
var re = /[^a-z]/g,
txt = navsel.options[i].text.split(" ")[0], // here I get the text from a select and I split it.
txt = txt.replace(re," ");
Or if you prefer strings (and a more explicit type):
var re = new RegExp("[^a-z]", "g")

What regex can I use to extract the URL from an HTTP <a> element?

Here is the Original string :
var str = " a vartiable";
and I need this part:
str = "https://sjobs.brassring.com/1033/ASP/TG/cim_jobdetail.asp?SID=^cJgiKPhGBHyn5VRSb9gbJg0K2T88FrLqHyAtd6hd5pJ7JeXxNyq0VatKCq3jYWp/&jobId=385594&type=hotjobs&JobReqLang=141&JobSiteId=5239&JobSiteInfo=385594_5239&GQId=0";
In other words, I need to remove the tag <a> and the document.href value
Thanks guys.
How about:
var str = " a vartiable";
str.replace(/^<a href="(https.*?)cim_home\.asp.*?'(cim_jobdetail\.asp.*)'.*$/, "$1$2");
produces:
"https://sjobs.brassring.com/1033/ASP/TG/cim_jobdetail.asp?SID=^cJgiKPhGBHyn5VRSb9gbJg0K2T88FrLqHyAtd6hd5pJ7JeXxNyq0VatKCq3jYWp/&jobId=385594&type=hotjobs&JobReqLang=141&JobSiteId=5239&JobSiteInfo=385594_5239&GQId=0"
Something simple like the following should work...
href="(.*?)"
here's the code u want:
var str = ' a vartiable'
var url = /\"(.*?)\"/str
that's how you match, here's how you strip it out:
str.replace(/\"(.*?)\"/, "$1");
the \"(.*?)\" gives the first minimal set of characters between two " characters the id of $1 then the second argument to the replace function tells it to replace the whole string with what's contained in $1
Also, if you use jQuery, this becomes pretty trivial:
var url = $("a").attr("href");

Categories

Resources