I have two strings such as:
sometext~somemoretext~extratext
and
sometext~otherextratext
I wish to crop off the last tilde (~) and all text to the right. For instance, the above two strings would result in:
sometext~somemoretext
and
sometext
Thanks
lastIndexOf(char) returns the position of the last found occurrence of a specified value in a string
substring(from, to) extracts the characters from a string, between two specified indices, and returns the new sub string
For instance:
var txt = 'sometext~somemoretext~extratext';
txt = txt.substring(0, txt.lastIndexOf('~'));
DEMO
I strongly suggest you to read the doc on the Javascript String Object
return theString.replace(/~[^~]*$/, '');
You can do this using a regular expression with the .replace() DOCs method.
var str = 'sometext~somemoretext~extratext';
str = str.replace(/~[\w\s]+$/, '');
Here is a jsFiddle of the above code for you to run: http://jsfiddle.net/NELFB/
you can use substr to split the string, then rebuild them for what ever you need
var someString = "sometext~otherextratext";
someString = someString.split('~');
this will give you an array, which you can use like someString[0];
use .replace('~', '') if you need to further remove the ones at the end of strings
this should do it
function removeExtra(input){
return input.substr(0,input.lastIndexOf('~'))
}
Related
i have this string => someRandomText&ab_channel=thisPartCanChange and i want to delete all from & (inclusive) to the end [this part: &ab_channel=thisPartCanChange].
How can i do this?
You van try something like:
console.log("someRandomText&ab_channel=thisPartCanChange".split("&")[0])
const yourString = 'SomeRandomText&ab_channel=thisPartCanChange'
console.log(yourString.split('&ab_channel')[0])
I would do a regex replacement on &.*$ and replace with empty string.
var inputs = ["someRandomText&ab_channel=thisPartCanChange", "someRandomText"];
inputs.forEach(x => console.log(x.replace(/&.*$/, "")));
Note that the above approach is robust with regard to strings which don't even have a & component.
You can use substring which extract the characters between two specified index without changing the original string
const yourString = 'someRandomText&ab_channel=thisPartCanChange';
const newStr = yourString.substring(0, yourString.indexOf('&'));
console.log(newStr)
I've looked all over the web but couldnt find a good answer to this. I need to write a function that finds the first word in a string/sentence. Its in relation to a html/css/javascript assignment, where i need to color or mark the first word in a long string, containing a story.
I'm thinking a simple for loop could do it, but cant get it to work.
The String global object is a constructor for strings or a sequence of characters.
in javascript String object has methods on his prototype - MDN - String
String.prototype.split() - Reference (MDN)
The split() method splits a String object into an array of strings by separating the string into substrings, using a specified separator string to determine where to make each split.
because you want to split by words, you should split string by "space".
as you can see split method on string return an array, so the first item in array will be the first word.
'Some String Here'.split(' ')[0];
Good Luck!
// Get Results Element
var div = document.querySelector('.results');
// Some string
var someString = 'Hi Hello JavaScript World';
function renderFirstWorkAsMarked(string, color) {
var splitedString = string.split(' ');
var wrapper = document.createElement('div')
var marked = document.createElement('span');
var restString = document.createTextNode(splitedString.slice(1).join(' '))
marked.style.color = color;
marked.innerHTML = `${splitedString[0]} `;
wrapper.appendChild(marked)
wrapper.appendChild(restString)
return wrapper
}
// append on screen
div.append(renderFirstWorkAsMarked(someString, 'red'))
// This is example code for your full question.
<div class="results"></div>
This will do the trick. It splits the string by the whitespace and then provides you the first word using the index.
"Plane Jane Mane".split(" ")[0]
Here's an example, the first console log will show you the formed array, and the second will select the first word in the array:
var word = "Plane Jane Mane"
console.log(word.split(" "))
console.log(word.split(" ")[0])
I answer your question with ES6 arrow function. see below code:
const firstWord = string => string.split(' ')[0];
Or you can use regex but I prefer the first function:
const firstWord = string => string.match(/^[\w\d]+/gs)[0];
let string = 'This is a sentence';
let word = string.split(' ')[0];
console.log(word);
Firstly, split sentences. Secondly, Split words and take first:
yourtext
.split(/(?<!\w\.\w.)(?<![A-Z][a-z]\.)(?<=\.|\?)\s/g)
.map(w => w.split(/((\b[^\s]+\b)((?<=\.\w).)?)/g)[1])
Example
I've looked all over the web but couldnt find a good answer to this. I need to write a function that finds the first word in a string/sentence. Its in relation to a html/css/javascript assignment, where i need to color or mark the first word in a long string, containing a story.
I'm thinking a simple for loop could do it, but cant get it to work.
Result
I've,I,Its,I'm
I need to remove all characters of a string after 5th character,
for example
my string is
P-CI-7-C-71
and the output should be like
P-CI-
Use substring
alert("P-CI-7-C-71".substring(0, 5));
So you can use it like
var str='P-CI-7-C-71'.substring(0, 5);
You can also use substr, that will work the same in this case but remember they work differently so they are not generally interchangeable
var str='P-CI-7-C-71'.substr(0, 5);
Difference can be noticed in the prototype
str.substring(indexStart[, indexEnd])
VS
str.substr(start[, length])
Extracting String Parts
There are 3 methods for extracting a part of a string:
slice(start, end)
substring(start, end)
substr(start, length)
With String#substring:
The substring() method returns a subset of a string between one index and another, or through the end of the string.
document.write('P-CI-7-C-71'.substring(0, 5));
Try this:
alert('P-CI-7-C-71'.substring(0,5));
var str = 'P-CI-7-C-71';
var res = str.slice(0,5);
alert(res);
Use Can use substring function in the JS
the Substring(StringName,StartPosition, End Position);
I have the following strings
"www.mywebsite.com/alex/bob/a-111/..."
"www.mywebsite.com/alex/bob/a-222/..."
"www.mywebsite.com/alex/bob/a-333/...".
I need to find the a-xxx in each one of them and use it as a different string.
Is there a way to do this?
I tried by using indexOf() but it only works with one character. Any other ideas?
You can use RegExp
var string = "www.mywebsite.com/alex/bob/a-111/...";
var result = string.match(/(a-\d+)/);
console.log(result[0]);
or match all values
var strings = "www.mywebsite.com/alex/bob/a-111/..." +
"www.mywebsite.com/alex/bob/a-222/..." +
"www.mywebsite.com/alex/bob/a-333/...";
var result = strings.match(/a-\d+/g)
console.log(result.join(', '));
Use the following RegEx in conjunction with JS's search() API
/(a)\-\w+/g
Reference for search(): http://www.w3schools.com/js/js_regexp.asp
var reg=/a-\d{3}/;
text.match(reg);
I am doing some JavaScript coding and have to process a string to a array.
The original string is this: "red,yellow,blue,green,grey"
What I want to get is an array like this: ["red","yellow","blue","green","grey"]
I have tried to write a function to do this, use indexOf() to get the position of commas then do some further processing. But I think it's to heavy this way. Is there a better way to use regular expression or some existed JavaScript method to implement my purpose?
Thanks all.
use string.split function to split the original string by comma.......
string.split(",")
You can use split:
The split() method splits a String object into an array of strings by separating the string into substrings.
var arr = "red,yellow,blue,green,grey".split(',');
OR
You can also use regex:
var arr = "red,yellow,blue,green,grey".match(/\w+/g);
Try the string.split() method. For further details refer to:
http://www.w3schools.com/jsref/jsref_split.asp
var str = "red,yellow,blue,green,grey";
var res = str.split(",");
you can use .split() function.
Example
.split() : Split a string into an array of substrings:
var str = "red,yellow,blue,green,grey";
var res = str.split(",");
alert(res);
You can use following regular expression ..
[^,]*