Replace in javascript - javascript

I have a string something like this:
http://stackoverflow.com/questions/ask
And would like to return this part:
http://stackoverflow.com/questions/
How can I do this using pure javascript?
Thanks!

This will match and remove the last part of a string after the slash.
url = "http://stackoverflow.com/questions/ask"
base = url.replace(/[^/]*$/, "")
document.write(base)
Help from: http://www.regexr.com/

For slicing off last part:
var test = 'http://stackoverflow.com/questions/ask';
var last = test.lastIndexOf('/');
var result = test.substr(0, last+1);
document.write(result);

You can accomplish this with the .replace() method on String objects.
For example:
//Regex way
var x = "http://stackoverflow.com/questions/ask";
x = x.replace(/ask/, "");
//String way
x = x.replace('ask', "");
//x is now equal to the string "http://stackoverflow.com/questions/"
The replace method takes two parameters. The first is what to replace, which can either be a string or regex, literal or variable, and the second parameter is what to replace it with.

Related

Using RegExp to substring a string at the position of a special character

Suppose I have a sting like this: ABC5DEF/G or it might be ABC5DEF-15 or even just ABC5DEF, it could be shorter AB7F, or AB7FG/H.
I need to create a javascript variable that contains the substring only up to the '/' or the '-'. I would really like to use an array of values to break at. I thought maybe to try something like this.
...
var srcMark = array( '/', '-' );
var whereAt = new RegExp(srcMark.join('|')).test.str;
alert("whereAt= "+whereAt);
...
But this returns an error: ReferenceError: Can't find variable: array
I suspect I'm defining my array incorrectly but trying a number of other things I've been no more successful.
What am I doing wrong?
Arrays aren't defined like that in JavaScript, the easiest way to define it would be with:
var srcMark = ['/','-'];
Additionally, test is a function so it must be called as such:
whereAt = new RegExp(srcMark.join('|')).test(str);
Note that test won't actually tell you where, as your variable suggests, it will return true or false. If you want to find where the character is, use String.prototype.search:
str.search(new RegExp(srcMark.join('|'));
Hope that helps.
You need to use the split method:
var srcMark = Array.join(['-','/'],'|'); // "-|/" or
var regEx = new RegExp(srcMark,'g'); // /-|\//g
var substring = "222-22".split(regEx)[0] // "222"
"ABC5DEF/G".split(regEx)[0] // "ABC5DEF"
From whatever i could understand from your question, using this RegExp /[/-]/ in split() function will work.
EDIT:
For splitting the string at all special characters you can use new RegExp(/[^a-zA-Z0-9]/) in split() function.
var arr = "ABC5DEF/G";
var ans = arr.split(/[/-]/);
console.log(ans[0]);
arr = "ABC5DEF-15";
ans = arr.split(/[/-]/);
console.log(ans[0]);
// For all special characters
arr = "AB7FG/H";
ans = arr.split(new RegExp(/[^a-zA-Z0-9]/));
console.log(ans[0]);
You can use regex with String.split.
It will look something like that:
var result = ['ABC5DEF/G',
'ABC5DEF-15',
'ABC5DEF',
'AB7F',
'AB7FG/H'
].map((item) => item.split(/\W+/));
console.log(result);
That will create an Array with all the parts of the string, so each item[0] will contain the text till the / or - or nothing.
If you want the position of the special character (non-alpha-numeric) you can use a Regular Expression that matches any character that is not a word character from the basic Latin alphabet. Equivalent to [^A-Za-z0-9_], that is: \W
var pattern = /\W/;
var text = 'ABC5DEF/G';
var match = pattern.exec(text);
var position = match.index;
console.log('character: ', match[0]);
console.log('position: ', position);

How to use split in javascript

I have a string like
/abc/def/hij/lmn.o // just a raw string for example dont know what would be the content
I want only /abc/def/hij part of string how do I do that.
I tried using .split() but did not get any solution.
If you want to remove the particular string /lmn.o, you can use replace function, like this
console.log(data.replace("/lmn.o", ""));
# /abc/def/hij
If you want to remove the last part after the /, you can do this
console.log("/" + data.split("/").slice(1, -1).join("/"));
# /abc/def/hij
you can do
var str = "/abc/def/hij/lmn.o";
var dirname = str.replace(/\/[^/]+$/, "");
Alternatively:
var dirname = str.split("/").slice(0, -1).join("/");
See the benchmarks
Using javascript
var x = '/abc/def/hij/lmn.o';
var y = x.substring(0,x.lastIndexOf("/"));
console.log(y);
var s= "/abc/def/hij/lmn.o"
var arr= s.split("/");
after this, use
arr.pop();
to remove the last content of the array which would be lmn.o, after which you can use
var new_s= arr.join("/");
to get /abc/def/hij

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 to save a removed string in a new string

I have this function :
string = string.replace(/^.*?([a-zA-Z])/, '$1');
and I'd like to save both strings : the one after the expression and the one removed.
How can I do it?
<script type="text/javacript">
var str = '44234lol';
var parts = str.split(/([a-zA-Z]+)/);
alert(parts[0]);
alert(parts[1]);
</script>
This would show what was removed from the original string and what you're left with (I've altered your regex but you could use the same technique) -
var portionremoved;
var string = '1234GF'
string = string.replace(/(\d+)([A-Z]+)/,function (removed,first,second) {
portionremoved = first;
return second;
});
alert(portionremoved);
alert(string);
string1 = string.replace(/^.*?([a-zA-Z])/, '$1');
Note that string.replace returns the replaced string while string still holds the previous value.

How to remove part of a string?

Let’s say I have test_23 and I want to remove test_.
How do I do that?
The prefix before _ can change.
My favourite way of doing this is "splitting and popping":
var str = "test_23";
alert(str.split("_").pop());
// -> 23
var str2 = "adifferenttest_153";
alert(str2.split("_").pop());
// -> 153
split() splits a string into an array of strings using a specified separator string.
pop() removes the last element from an array and returns that element.
If you want to remove part of string
let str = "try_me";
str.replace("try_", "");
// me
If you want to replace part of string
let str = "try_me";
str.replace("try_", "test_");
// test_me
Assuming your string always starts with 'test_':
var str = 'test_23';
alert(str.substring('test_'.length));
Easiest way I think is:
var s = yourString.replace(/.*_/g,"_");
string = "test_1234";
alert(string.substring(string.indexOf('_')+1));
It even works if the string has no underscore. Try it at http://jsbin.com/
let text = 'test_23';
console.log(text.substring(text.indexOf('_') + 1));
You can use the slice() string method to remove the begining and end of a string
const str = 'outMeNo';
const withoutFirstAndLast = str.slice(3, -2);
console.log(withoutFirstAndLast);// output--> 'Me'

Categories