String manipulation using MooTools / JavaScript - javascript

How do I manipulate a string using MooTools / JavaScript
I would like to replace all after /p/ in following url:
http://example.com/groups/browse/catId/14/p/1000-1500
Expected result:
http://example.com/groups/browse/catId/14

That doesn't look like you want to replace, it looks like you want to remove.
You can do that with regular string operations in plain Javascript:
var s = "http://example.com/groups/browse/catId/14/p/1000-1500";
s = s.substr(0, s.indexOf("/p/")));

Simple enough with regex:
var url = "http://example.com/groups/browse/catId/14/p/1000-1500";
console.log(url.replace(/\/p\/.+/, ""));
//-> "http://example.com/groups/browse/catId/14"
In the regex above, \/p\/ is /p/ with escaped slashes, followed by .+ which means match any character (except white space) one or more times.
You can brush up on your JavaScript regular expressions at http://www.regular-expressions.info/javascript.html.

you don't have to use mootools necessarily. you can split the string with split function from javascript
var myString = 'http://example.com/groups/browse/catId/14/p/1000-1500';
newString = myString.split('/p/');
alert(newString[0]);

Related

Unable to replace a substring in a string

I can't replace the substring in a string:
var source = "div.col-md-4.fields:visible:eq(0) div.panel-body select:eq(0)";
var modified = source.replace(/visible:eq(0)/g, "1234");
I wonder why does modified have the same value as source?
You should not use regular expressions here but a simple string replace function. It will run faster and regular expressions were not made for simple tasks like this as they will run slightly slower than the simple replace function. Using regular expressions here is like using a nuke to open a water bottle, rather prefer simplicity, if a developer sees this code he will like the simplicity.
Change your second line to this one:
var modified = source.replace("visible:eq(0)", "1234");
You need to escape the brackets
var source = "div.col-md-4.fields:visible:eq(0) div.panel-body select:eq(0)";
var modified = source.replace(/visible:eq\(0\)/g, "1234");
console.log(source);
console.log(modified);
You just need to escape your chars like this Demo: http://jsfiddle.net/cvW24/1/
hope rest help the cause :)
if you keen:
Need to escape a special character in a jQuery selector string
http://api.jquery.com/category/selectors/
code
var source = "div.col-md-4.fields:visible:eq(0) div.panel-body select:eq(0)";
var modified = source.replace(/visible:eq\(0\)/g, "1234");
alert(modified);
Because your regular expression does not match the string. You need to escape the parenthesis.
var modified = source.replace(/visible:eq\(0\)/g, "1234");

jQuery / Javascript replace multiple occurences not working

I'm trying to replace multiple occurrences of a string and nothing seems to be working for me. In my browser or even when testing online. Where am I going wrong?
str = '[{name}] is happy today as data-name="[{name}]" won the match today. [{name}] made 100 runs.';
str = str.replace('/[{name}]/gi','John');
console.log(str);
http://jsfiddle.net/SXTd4/
I got that example from here, and that too wont work.
You must not quote regexes, the correct notation would be:
str = str.replace(/\[{name}\]/gi,'John');
Also, you have to escape the [], because otherwise the content inside is treated as character class.
Updating your fiddle accordingly makes it work.
There are two ways declaring regexes:
// literal notation - the preferred option
var re = /regex here/;
// via constructor
var re = new Regexp('regex here');
You should not put your regex in quotes and you need to escape []
Simply use
str = str.replace(/\[{name}\]/gi,'John');
DEMO
While there are plenty of regex answers here is another way:
str = str.split('[{name}]').join('John');
The characters [ ] { } should be escaped in your regular expression.

Split each string from any given paragraph in javascript

I have a textArea. I am trying to split each string from a paragraph, which has proper grammar based punctuation delimiters like ,.!? or more if any.
I am trying to achieve this using Javascript. I am trying to get all such strings in that using the regular expression as in this answer
But here, in javascript for me it's not working. Here's my code snippet for more clarity
$('#split').click(function(){
var textAreaContent = $('#textArea').val();
//split the string i.e.., textArea content
var splittedArray = textAreaContent.split("\\W+");
alert("Splitted Array is "+splittedArray);
var lengthOfsplittedArray = splittedArray.length;
alert('lengthOfText '+lengthOfsplittedArray);
});
Since its unable to split, its always showing length as 1. What could be the apt regular expression here.
The regular expression shouldn't differ between Java and JavaScript, but the .split() method in Java accepts a regular expression string. If you want to use a regular expression in JavaScript, you need to create one...like so:
.split(/\W+/)
DEMO: http://jsfiddle.net/s3B5J/
Notice the / and / to create a regular expression literal. The Java version needed two "\" because it was enclosed in a string.
Reference:
https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Regular_Expressions
You can try this
textAreaContent.split(/\W+/);
\W+ : Matches any character that is not a word character (alphanumeric & underscore).
so it counts except alphanumerics and underscore! if you dont need to split " " (space) then you can use;
var splittedArray = textAreaContent.split("/\n+/");

Replace Characters from string with javascript

I have a string like (which is a shared path)
\\cnyc12p20005c\mkt$\\XYZ\
I need to replace all \\ with single slash so that I can display it in textbox. Since it's a shared path the starting \\ should not be removed. All others can be removed.
How can I achieve this in JavaScript?
You could do it like this:
var newStr = str.replace(/(.)\\{2}/, "$1\\");
Or this, if you don't like having boobs in your code:
var newStr = "\\" + str.split(/\\{1,2}/).join("\\");
You can use regular expression to achieve this:
var s = '\\\\cnyc12p20005c\\mkt$\\\\XYZ\\';
console.log(s.replace(/.\\\\/g, '\\')); //will output \\cnyc12p20005c\mkt$\XYZ\
Double backslashes are used because backslash is special character and need to be escaped.

Split string in JavaScript using a regular expression

I'm trying to write a regex for use in javascript.
var script = "function onclick() {loadArea('areaog_og_group_og_consumedservice', '\x26roleOrd\x3d1');}";
var match = new RegExp("'[^']*(\\.[^']*)*'").exec(script);
I would like split to contain two elements:
match[0] == "'areaog_og_group_og_consumedservice'";
match[1] == "'\x26roleOrd\x3d1'";
This regex matches correctly when testing it at gskinner.com/RegExr/ but it does not work in my Javascript. This issue can be replicated by testing ir here http://www.regextester.com/.
I need the solution to work with Internet Explorer 6 and above.
Can any regex guru's help?
Judging by your regex, it looks like you're trying to match a single-quoted string that may contain escaped quotes. The correct form of that regex is:
'[^'\\]*(?:\\.[^'\\]*)*'
(If you don't need to allow for escaped quotes, /'[^']*'/ is all you need.) You also have to set the g flag if you want to get both strings. Here's the regex in its regex-literal form:
/'[^'\\]*(?:\\.[^'\\]*)*'/g
If you use the RegExp constructor instead of a regex literal, you have to double-escape the backslashes: once for the string literal and once for the regex. You also have to pass the flags (g, i, m) as a separate parameter:
var rgx = new RegExp("'[^'\\\\]*(?:\\\\.[^'\\\\]*)*'", "g");
while (result = rgx.exec(script))
print(result[0]);
The regex you're looking for is .*?('[^']*')\s*,\s*('[^']*'). The catch here is that, as usual, match[0] is the entire matched text (this is very normal) so it's not particularly useful to you. match[1] and match[2] are the two matches you're looking for.
var script = "function onclick() {loadArea('areaog_og_group_og_consumedservice', '\x26roleOrd\x3d1');}";
var parameters = /.*?('[^']*')\s*,\s*('[^']*')/.exec(script);
alert("you've done: loadArea("+parameters[1]+", "+parameters[2]+");");
The only issue I have with this is that it's somewhat inflexible. You might want to spend a little time to match function calls with 2 or 3 parameters?
EDIT
In response to you're request, here is the regex to match 1,2,3,...,n parameters. If you notice, I used a non-capturing group (the (?: ) part) to find many instances of the comma followed by the second parameter.
/.*?('[^']*')(?:\s*,\s*('[^']*'))*/
Maybe this:
'([^']*)'\s*,\s*'([^']*)'

Categories