如何拆分出现" users /"的字符串?从URL?

时间:2017-11-13 09:29:40

标签: ios swift

我使用的是这种方法,这是我的网址" https://www.youtube.com/user/myYoutubeChennal"。我想得到" myYoutubeChennal"从此。

class ClientList extends Component {

    constructor(props) {
        super(props);

        this.state = {
            clientId : ''

        }
        this.getClientList = this.getClientList.bind(this);
        this.showList = this.showList.bind(this);
        console.log('initializing', this.props);
    }

    componentDidMount(){
        this.getClientList();
    }

    getClientList() {
        if (this.props.actions) {
        this.props.actions.getClientList(); //This is an ajax action to retrieve from Api
        }

    }

    showList() {

            //If i put all the codes below directly in Render, it will show.
            console.log('props from showList', this.props.clientList);

                        this.props.clientList && Object.keys(this.props.clientList).reverse().map((index,key) => {

                     return (

                     <div key={key}>
                     <div><a onClick={() => this.showProfileBox(this.props.clientList[index].customerId)}>Name: {this.props.clientList[index].firstname} {this.props.clientList[index].lastname}</a><span className="pull-right"><Link to={"/client/" + this.props.clientList[index].customerId}>Edit</Link></span></div>

                     </div>
                    );
                })
        }

    render() {
        console.log('rendering', this.props);
        return (

                <div>

                <Col xs={12} md={8}>
                <h1>Client List</h1>

                { this.showList() }  // <= This function doesn't print
                </Col>

                </div>
            )
    }

}

function mapStateToProps(state) {

    return {
        clientList: state.clientList,

    };
}

function mapDispatchToProps(dispatch) {  
  return {
    actions: bindActionCreators(clientActions, dispatch)
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(ClientList);

2 个答案:

答案 0 :(得分:3)

您可以使用以下代码

获取网址的最后一个组成部分
let url = URL(string:"https://www.youtube.com/user/myYoutubeChennal")
let lastComponent = url?.lastPathComponent

答案 1 :(得分:1)

假设所需的字符串始终是user用斜杠拆分字符串后的路径组件,请获取user的索引,然后获取项index + 1

let string = "https://www.youtube.com/user/myYoutubeChennal"
let components = string.components(separatedBy: "/")
if let index = components.index(of: "user"), index < components.count - 1 {
    let user = components[index + 1]
} else {
   print("user not found")
}