Regular Expression in single statement - javascript

var str = "test's t\r and t\n";
str = str.replace(/'/g, "\'");
str = str.replace(/\r/g, "\\r");
str = str.replace(/\n/g,"\\n");
Is it possible to do these 3 replaces in single statement?
I want escape these particular chars. With out escaping it makes some problem. "\n" following chars goes to next line. While passing this as parameter it ll not get it as "\n" in the server.

Try this:
str.replace(/'|\r|\n/g, function($0) {
var trans = {"\r":"r", "\n":"n"};
return "\\" + (trans.hasOwnProperty($0) ? trans[$0] : $0);
})

You can also chain them:
var str = "test's t\r and t\n";
str = str.replace(/'/g, "\'").replace(/\r/g, "\\r").replace(/\n/g,"\\n");

var str = "test's t\r and t\n";
str = str.replace(/(\'|\r\n|\r|\n)/g, "\\");
alert("++++++++++++"+str+"++++++++++++");

Related

Make string comma delimited in JavaScript

I have a string:
var myStr = 'This is a test';
I would like to make it comma delimited via JavaScript, like so:
var myNewStr = 'This, is, a, test';
What is the best way to accomplish this via JavaScript?
I know I can trim the commas like so:
var myStr = myNewStr.split(',');
And that would give me this:
myStr = 'This is a test';
But I am wanting to do the opposite of course, by adding commas.
You could just replace with regex - it is shorter and no need to split.
var myNewStr = myStr.replace(/ /g,', ');
In case you could also face the string with leading / trailing spaces, just trim it beforehand.
var myNewStr = myStr.trim().replace(/ /g,', ');
Try this - var myNewStr = myStr.split(' ').join(', ')
You could use a regular expression with a positive lookahead and replace then with a comma.
console.log('This is a test'.replace(/(?= .)/g, ','));
console.log('This is a test '.replace(/(?= .)/g, ','));
Use String.replace:
var myStr = 'This is a test';
var myNewStr=myStr.replace(/ /g,', ');
You could use the replace function to replace the spaces with commas:
var myStr = myNewStr.replace(' ', ',');
You could also use:
var myStr = myNewStr.split(' ');
Here is a way to do it without using the standard methods.
var myStr = "THIS IS A TEST";
before.innerHTML = myStr;
var parts = [];
var buffer = '';
for(var i = 0; i < myStr.length; i++) {
if(myStr[i] == ' ') {
parts.push(buffer);
buffer = '';
continue;
} else {
buffer += myStr[i];
}
}
parts.push(buffer)
var myNewStr = parts.join(', ');
after.innerHTML = myNewStr;
<div><b>Before</b></div>
<div id="before"></div>
<div><b>After</b></div>
<div id="after"></div>
The solution using String.trim and String.replace functions:
var myStr = ' This is a test ',
myNewStr = myStr.trim().replace(/([^\s]+\b)(?!$)/g, "$&,");
// $& - Inserts the matched substring.
console.log(myNewStr); // "This, is, a, test"

Javascript regex get string before second /

var str = '#/promotionalMailer/test1';
output should be ==> #/promotionalMailer
I want the string before the second slash '/'
I have tried this so far:
var str = '#/promotionalMailer/test1';
var match = str.match(/([^\/]*\/){2}/)[0];
alert(match);
But it comes with the second slash.
try split, slice and join
var str = '#/promotionalMailer/test1';
console.log( str.split("/").slice(0,2).join("/"));
For example,
var str = '#/promotionalMailer/test1/foo/bar/baz';
result = str.split('/').slice(0, 2).join('/')
document.write('<pre>'+JSON.stringify(result,0,3));
If you want regexes, then
var str = '#/promotionalMailer/test1/foo/bar/baz';
result = str.match(/[^\/]*\/[^\/]*/)[0]
document.write('<pre>'+JSON.stringify(result,0,3));

How to cut third symbol from string and alert it without third symbol

How can i correctly cut out letter "v" and alert str without "v"
var str = "Javascript";
var cut = str.substring(2,3);
var str = "Javascript";
var cut = str.substring(0,2) + str.substring(3);
alert(cut);
You're using the right tool (String#substring). You need two substrings that you put back together, the "Ja" and the "ascript". So:
var str = "Javascript";
var cut = str.substring(0, 2) + str.substring(3);
alert(cut);
Another option would be String#replace, which will replace the first occurrence of what you give it unless you tell it to do it globally with a regex and the g flag (which we won't, because we just want to remove that one v):
var str = "Javascript";
var cut = str.replace("v", "");
alert(cut);
Just for fun, there is another way, but it's a bit silly: You can split the string into an array of single-character strings, remove the third entry from the array, and then join it back together:
var str = "Javascript";
var cut = str.split("").filter(function(_, index) {
return index != 2;
}).join("");
alert(cut);
or
var str = "Javascript";
var cut = str.split("");
cut.splice(2, 1); // Delete 1 entry at index 2
cut = cut.join("");
alert(cut);
...but again, that's a bit silly. :-)
use replace method
var str = "Javascript";
str = str.replace("v", "");
alert(str);

How to get particular string from one big string ?

I have string
var str = "Ahora MXN$1,709.05" and wanted to get only
"MXN$1,709.05" from this.
Can someone please help me?
You can use substring or replace. With replace you are going to replace something with nothing.
replace
var str = 'Ahora MXN$1,709.05';
var sub = 'Ahora ';
var res = str.replace(sub,'');
substring
var str = 'Ahora MXN$1,709.05';
var sub = 'Ahora ';
var res = str.substring(sub.length);
JsFiddle
You can use either substring or Regex
Using substring
var str = "Ahora MXN$1,709.05";
var result = str.substring('Ahora '.length);
console.log(result);
Using Regex
var str = "Ahora MXN$1,709.05";
var myRegexp = /Ahora\s(.*?)(?:\s|$)/g;
var match = myRegexp.exec(str);
console.log(match[1]);

Replace each leading and trailing whitespace with underscore using regex in javascript

var str = ' Some string ';
var output = str.replace(/^\s|\s(?=\s*$)/g , '_');
The output should look like this
'___Some string____'
This code works fine for the trailing whitespaces but all the leading whitespaces are replaced with just one underscore.
The working php regex for this is: /\G\s|\s(?=\s*$)/
Not pretty, but gets the job done
var str = " Some string ";
var newStr = str.replace(/(^(\s+)|(\s+)$)/g,function(spaces){ return spaces.replace(/\s/g,"_");});
This works but I don't like it:
var str = " some string ";
var result = str.replace(/^\s+|\s+$/g, function(m) {
return '________________________________________'.substring(0, m.length);
});
Or more flexibly:
var str = " some string ";
var result = str.replace(/^\s+|\s+$/g, function(m) {
var rv = '_',
n;
for (n = m.length - 1; n > 0; --n) {
rv += '_';
}
return rv;
});
That can be refined, of course.
But I like epascarello's answer better.
another reg ex
var str = " asdf "
str.replace(/^[ ]+|[ ]+$/g,function(spc){return spc.replace(/[ ]/g,"_")})
//"__asdf_______"
With String.prototype.repeat() the accepted answer can now be improved to
function replaceLeadingAndTrailingWhitespace(text, replace) {
return text.replace(/^\s+|\s+$/g, (spaces) => replace.repeat(spaces.length));
}

Categories