简体   繁体   中英

Splitting string with javascript using '>' character

I acknowledge that this question has probably been asked so many times before and I have tried searching all over StackOverflow for a solution, but so far nothing has worked for me.

I want to split a string but it's not working properly and spitting out individual characters as each item in an array. The string I have from my CMS uses ">" characters to separate and I am using regEx to replace the 'greater than' symbol - with a comma, which works. Sourced this solution from Regex that detects greater than ">" and less than "<" in a string

However, the arrays remain incorrectly formed, like the split() function does not even work:

var myString = "TEST Public Libraries Connect > News Blog > A new item"

var regEx = /<|>/g;
var myNewString = (myString.replace(regEx,","))
alert(myNewString);

myNewString.split(",");
alert(myNewString[0]);
alert(myNewString[1]);
alert(myNewString[2]);

I've put it up in a Fiddle as well, just confused as to why the split won't work properly. Is it because there is spaces in the string?

myNewString.split(",");

You need to assign the result of the split to something. It does not just change the string itself into an array.

var parts = myNewString.split(",");

This should work:

var myNewString = myString.split(">");

https://jsfiddle.net/2j56cva0/3/

In your fiddle, you were splitting myNewString instead of the actual string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM