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.
Related
I have a string like "home/back/step" new string must be like "home/back".
In other words, I have to remove the last word with '/'. Initial string always has a different length, but the format is the same "word1/word2/word3/word4/word5...."
var x = "home/back/step";
var splitted = x.split("/");
splitted.pop();
var str = splitted.join("/");
console.log(str);
Take the string and split using ("/"), then remove the last element of array and re-join with ("/")
Use substr and remove everything after the last /
let str = "home/back/step";
let result = str.substr(0, str.lastIndexOf("/"));
console.log(result);
You could use arrays to remove the last word
const text = 'home/back/step';
const removeLastWord = s =>{
let a = s.split('/');
a.pop();
return a.join('/');
}
console.log(removeLastWord(text));
Seems I got a solution
var s = "your/string/fft";
var withoutLastChunk = s.slice(0, s.lastIndexOf("/"));
console.log(withoutLastChunk)
You can turn a string in javascript into an array of values using the split() function. (pass it the value you want to split on)
var inputString = 'home/back/step'
var arrayOfValues = inputString.split('/');
Once you have an array, you can remove the final value using pop()
arrayOfValues.pop()
You can convert an array back to a string with the join function (pass it the character to place in between your values)
return arrayOfValues.join('/')
The final function would look like:
function cutString(inputString) {
var arrayOfValues = inputString.split('/')
arrayOfValues.pop()
return arrayOfValues.join('/')
}
console.log(cutString('home/back/step'))
You can split the string on the '/', remove the last element with pop() and then join again the elements with '/'.
Something like:
str.split('/');
str.pop();
str.join('/');
Where str is the variable with your text.
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.
how to convert this string to float?
i want result 900.50
case-1: var convertThis = 'any string here 900,50 also any string here';
case-2: var convertThis = 'any string here 900.50 also any string here';
How to do this?
Try following code:
var text = 'any string here 900,50 also any string here';
var matched = text.match(/\d+[,.]\d+/)[0].replace(',', '.');
var num = parseFloat(matched, 10);
console.log(matched);
console.log(num);
prints:
900.50
900.5
You could do this :
var num = parseFloat(convertThis.replace(/[^\d\.,]/g,'').replace(/,/,'.'));
But be aware that this would break as soon as you have more than one number or dot in your text. If you want something reliable, you need to be more precise about what the string can be.
Supposing you'd want to extract all numbers from a more complex strings, you could do
var numbers = convertThis.split(/\s/).map(function(s){
return parseFloat(s.replace(',','.'))
}).filter(function(v) { return v });
Here, you'd get [900.5]
var myFloat = +(convertThis.match(/\d+[,\.]?\d+/)[0].replace(",","."))
How do you trim all of the text after a comma using JS?
I have: string = Doyletown, PA
I want: string = Doyletown
var str = 'Doyletown, PA';
var newstr=str.substring(0,str.indexOf(',')) || str;
I added the || str to handle a scenario where the string has no comma
How about a split:
var string = 'Doyletown, PA';
var parts = string.split(',');
if (parts.length > 0) {
var result = parts[0];
alert(result); // alerts Doyletown
}
using regular expression it will be like:
var str = "Doyletown, PA"
var matches = str.match(/^([^,]+)/);
alert(matches[1]);
jsFiddle
btw: I would also prefer .split() method
Or more generally (getting all the words in a comma separated list):
//Gets all the words/sentences in a comma separated list and trims these words/sentences to get rid of outer spaces and other whitespace.
var matches = str.match(/[^,\s]+[^,]*[^,\s]+/g);
Try this:
str = str.replace(/,.*/, '');
Or play with this jsfiddle
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'