Replacing carets in Javascript - javascript

I'm trying to replace multiple carets (^) in a string with spaces in Javascript. Following the w3schools entry on replace(), I used this code:
var str = "Salt^Lake^City, UT";
var result = str.replace(/^/g, " ");
However, value of result is " Salt^Lake^City, UT". One caret is replaced when I run this code:
var result = str.replace("^", " ");
but I want to replace all of an arbitrary number of carets. Is there something obvious I'm missing about globally replacing in Javascript? I could write a function using str.replace("^", " "); to remove all the carets, but I'd rather use the built-in global replace.

The ^ character matches the start of the string in a regex, so you need to escape it so it will be treated as a literal character. That is why in your example, the result string has a new space added at the start of the string.
var result = str.replace(/\^/g, " ");

You can also use another handy way which is roundabout.
var result = str.split('^').join(' ') ;

Related

Get replaced characters with javascript regex replace

I am currently replacing all non-letter characters using
var stringwithoutspecialCharacter = "testwordwithpunctiuation.".replace(/[^\w\s!?]/g, '');
The problem is that I do not know which special character will appear (that needs removing). However I do need to be able to access the removed special character after I've run some code with the word without the special character.
Example inputs:
"test".
(temporary)
foo,
Desired output:
['"','test','"',"."]
['(','temporary',')']
['foo',',']
How could this be achieved in javascript?
Edit: To get both valid and invalid characters, change the regular expression
Quick solution is to define an array to collect the matches.
Then pass in a function into your replace() call
var matches = [];
var matcher = function(match, offset, string) {
matches.push(match);
return '';
}
var stringwithoutspecialCharacter = "testwordwithpunctiuation.".replace(/[^\w\s!?]|[\w\s!?]+/g, matcher);
console.log("Matches: " + matches);

Finding image url via using Regex

Any working Regex to find image url ?
Example :
var reg = /^url\(|url\(".*"\)|\)$/;
var string = 'url("http://domain.com/randompath/random4509324041123213.jpg")';
var string2 = 'url(http://domain.com/randompath/random4509324041123213.jpg)';
console.log(string.match(reg));
console.log(string2.match(reg));
I tied but fail with this reg
pattern will look like this, I just want image url between url(" ") or url( )
I just want to get output like http://domain.com/randompath/random4509324041123213.jpg
http://jsbin.com/ahewaq/1/edit
I'd simply use this expression:
/url.*\("?([^")]+)/
This returns an array, where the first index (0) contains the entire match, the second will be the url itself, like so:
'url("http://domain.com/randompath/random4509324041123213.jpg")'.match(/url.*\("?([^")]+)/)[1];
//returns "http://domain.com/randompath/random4509324041123213.jpg"
//or without the quotes, same return, same expression
'url(http://domain.com/randompath/random4509324041123213.jpg)'.match(/url.*\("?([^")]+)/)[1];
If there is a change that single and double quotes are used, you can simply replace all " by either '" or ['"], in this case:
/url.*\(["']?([^"')]+)/
Try this regexp:
var regex = /\burl\(\"?(.*?)\"?\)/;
var match = regex.exec(string);
console.log(match[1]);
The URL is captured in the first subgroup.
If the string will always be consistent, one option would be simply to remove the first 4 characters url(" and the last two "):
var string = 'url("http://domain.com/randompath/random4509324041123213.jpg")';
// Remove last two characters
string = string.substr(0, string.length - 2);
// Remove first five characters
string = string.substr(5, string.length);
Here's a working fiddle.
Benefit of this approach: You can edit it yourself, without asking StackOverflow to do it for you. RegEx is great, but if you don't know it, peppering your code with it makes for a frustrating refactor.

I have a string and want to remove special chars in its specific part using javascript

I have a string looks like:
var myString= '{"key1":"value1", "key2":"value2", "key3":"value3"}';
What I want is to remove double qoutes and other special chars only from value3 ... for example some times we have string looks like:
var myString= '{"key1":"value1", "key2":"value2", "key3":"This is "value" with some special chars etc"}';
Please note I do not want to remove double quotes after colon and before This and similarly I do not want to remove last double quotes. I just want to modify string so it will become:
var myString = '{"key1":"value1", "key2":"value2", "key3":"This is value with some special chars etc"}';
Simple...
var myNewString = eval( '('+ myString +')');
var toBeEscaped = myNewString.key3;
var escapedString = doYourCleanUpStuff(toBeEscaped);
myNewString.key3 = escapedString;
myNewString = JSON.stringify(myNewString);
===============
What did I do?
1) Your string looks like valid JSON.
2) Cast it into JSON object. (using eval() )
3) Retrieve value of key3 and catch it in some temp variable.
4) Do cleanup things with this temporary variable.
5) assign cleaned up temporary variable back to key3.
6) Stringify the JSON.
Don't go around beating bush with array manipulation and split functions, especially when there are simpler ways :)
You will probably want to use the Array map function in conjunction with the string replace function.
To use the replace function, you'll probably want to use regular expressions. For example, the following regular expression will remove double quotes not immediately after a colon: [^:]".
To replace every quote not immediately followed by a colon in an array of strings, you could write this:
var myString= '{"key1":"value1", "key2":"value2", "key3":"value3"}';
var modified = myString.map(function(s) { return s.replace(/[^:]"/g, ''); });
Make your own modifications to the regular expression to match the characters you want to remove.
Refer to http://www.addedbytes.com/cheat-sheets/regular-expressions-cheat-sheet/.
First thing that comes to my mind is to isolate the Value you want.
You can .Split() for the value you want
var myString = '{"key1":"value1", "key2":"value2",
"key3":"value3"}';var n=str.split(" ");
var key3Value = str.split(//Based on your value);
//Run .replace() on your key3Value to replace your doublequotes, etc.
//Re-declare myString to include the updated key3Value
Sorry, no time at the moment to finish the code, and I am sure their are better/shorter answers than mine. Just wanted to include this as an option.

String manipulation - getting value after the last position of a char

How I can get the value after last char(. ; + _ etc.):
e.g.
string.name+org.com
I want to get "com".
Is there any function in jQuery?
Use lastIndexOf and substr to find the character and get the part of the string after it:
var extension = name.substr(name.lastIndexOf(".") + 1);
Demo: http://jsfiddle.net/Guffa/K3BWn/
A simple and readable approch to get the substring after the last occurrence of a character from a defined set is to split the string with a regular expression containing a character class and then use pop() to get the last element of the resulting array:
The pop() method removes the last element from an array and returns that element.
See a JS demo below:
var s = 'string.name+org.com';
var result = s.split(/[.;+_]/).pop();
console.log(result);
to split at all non-overlapping occurrences of the regex by default.
NOTE: If you need to match ^, ], \ or -, you may escape them and use anywhere inside the character class (e.g. /[\^\-\]\\]/). It is possible to avoid escaping ^ (if you do not put it right after the opening [), - (if it is right after the opening [, right before the closing ], after a valid range, or between a shorthand character class and another symbol): /[-^\]\\]/.
Also, if you need to split with a single char, no regex is necessary:
// Get the substring after the last dot
var result = 'string.name+org.com'.split('.').pop();
console.log(result);
Not jQuery, just JavaScript: lastIndexOf and substring would do it (not since the update indicating multiple characters). As would a regular expression with a capture group containing a character class followed by an end-of-string anchor, e.g. /([^.;+_]+)$/ used with RegExp#exec or String#match.
E.g. (live copy | source):
var match = /([^.;+_]+)$/.exec(theStringToTest),
result = match && match[1];
var s = "string.name+org.com",
lw = s.replace(/^.+[\W]/, '');
console.log(lw) /* com */
this will also work for
string.name+org/com
string.name+org.info
You can use RegExp Object.
Try this code:
"http://stackoverflow.com".replace(/.*\./,"");
I'll throw in a crazy (i.e. no RegExp) one:
var s = 'string.name+org.com';
var a = s.split('.'); //puts all sub-Strings delimited by . into an Array
var result = a[a.length-1]; //gets the last element of that Array
alert(result);​
EDIT: Since the update of the question is demanding mutiple delimiters to work this is probably not the way to go. Too crazy.....
use javascript function like
url.substr(url.length - 3);
maybe this is too late to consider, this codes works fine for me using jquery
var afterDot = value.substr(value.lastIndexOf('_') + 1);
You could just replate '_' to '.'
var myString = 'asd/f/df/xc/asd/test.jpg'
var parts = myString.split('/');
var answer = parts[parts.length - 1];
console.log(answer);

Replace multiple whitespaces with single whitespace in JavaScript string

I have strings with extra whitespace characters. Each time there's more than one whitespace, I'd like it be only one. How can I do this using JavaScript?
Something like this:
var s = " a b c ";
console.log(
s.replace(/\s+/g, ' ')
)
You can augment String to implement these behaviors as methods, as in:
String.prototype.killWhiteSpace = function() {
return this.replace(/\s/g, '');
};
String.prototype.reduceWhiteSpace = function() {
return this.replace(/\s+/g, ' ');
};
This now enables you to use the following elegant forms to produce the strings you want:
"Get rid of my whitespaces.".killWhiteSpace();
"Get rid of my extra whitespaces".reduceWhiteSpace();
Here's a non-regex solution (just for fun):
var s = ' a b word word. word, wordword word ';
// with ES5:
s = s.split(' ').filter(function(n){ return n != '' }).join(' ');
console.log(s); // "a b word word. word, wordword word"
// or ES2015:
s = s.split(' ').filter(n => n).join(' ');
console.log(s); // "a b word word. word, wordword word"
Can even substitute filter(n => n) with .filter(String)
It splits the string by whitespaces, remove them all empty array items from the array (the ones which were more than a single space), and joins all the words again into a string, with a single whitespace in between them.
using a regular expression with the replace function does the trick:
string.replace(/\s/g, "")
I presume you're looking to strip spaces from the beginning and/or end of the string (rather than removing all spaces?
If that's the case, you'll need a regex like this:
mystring = mystring.replace(/(^\s+|\s+$)/g,' ');
This will remove all spaces from the beginning or end of the string. If you only want to trim spaces from the end, then the regex would look like this instead:
mystring = mystring.replace(/\s+$/g,' ');
Hope that helps.
jQuery.trim() works well.
http://api.jquery.com/jQuery.trim/
I know I should not necromancy on a subject, but given the details of the question, I usually expand it to mean:
I want to replace multiple occurences of whitespace inside the string with a single space
...and... I do not want whitespaces in the beginnin or end of the string (trim)
For this, I use code like this (the parenthesis on the first regexp are there just in order to make the code a bit more readable ... regexps can be a pain unless you are familiar with them):
s = s.replace(/^(\s*)|(\s*)$/g, '').replace(/\s+/g, ' ');
The reason this works is that the methods on String-object return a string object on which you can invoke another method (just like jQuery & some other libraries). Much more compact way to code if you want to execute multiple methods on a single object in succession.
var x = " Test Test Test ".split(" ").join("");
alert(x);
Try this.
var string = " string 1";
string = string.trim().replace(/\s+/g, ' ');
the result will be
string 1
What happened here is that it will trim the outside spaces first using trim() then trim the inside spaces using .replace(/\s+/g, ' ').
How about this one?
"my test string \t\t with crazy stuff is cool ".replace(/\s{2,9999}|\t/g, ' ')
outputs "my test string with crazy stuff is cool "
This one gets rid of any tabs as well
If you want to restrict user to give blank space in the name just create a if statement and give the condition. like I did:
$j('#fragment_key').bind({
keypress: function(e){
var key = e.keyCode;
var character = String.fromCharCode(key);
if(character.match( /[' ']/)) {
alert("Blank space is not allowed in the Name");
return false;
}
}
});
create a JQuery function .
this is key press event.
Initialize a variable.
Give condition to match the character
show a alert message for your matched condition.

Categories